我想在应用的主要根组件中获取用户数据,然后在将用户数据存储到服务中后继续加载其他组件。我怎样才能做到这一点?目前,我有这样的东西:
@Injectable()
export class UserService {
user: Subject<User> = new BehaviorSubject(new User());
constructor(private _httpService: HTTPService){}
getUser(){
return this.user;
}
getUserFromAPI(){
this._httpService.get('user')
.map(data => data.json())
.subscribe(data => {
this.user.next(data);
});
}
但是通过这种方式,这意味着我需要通过我不想要的 Observable 让用户到达其他任何地方。我想要静态访问。 目前,我正在获取用户:
this._userService.getUser().subscribe(data => {
this.user = data;
});
最佳答案
您可以使用APP_INITIALIZER
Angularjs2 - preload server configuration before the application starts Angular 在数据可用之前等待渲染任何组件
或者您可以只使用 *ngIf
来防止在数据可用之前渲染组件
<ng-container *ngIf="data">
<child1></child1>
<child2></child2>
</ng-container>
关于Angular 2 在加载子组件之前获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41376233/