I want to get the user data in the main root component of the app and then after user data is stored into service to continue loading other components. How can I achieve this? Currently, I have something like this:
@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);
});
}
But with this way, it means that I need to get the user on every other place through the Observable which I don't want. I want to have a static access. Currently, I'm getting the user:
this._userService.getUser().subscribe(data => {
this.user = data;
});
You can use APP_INITIALIZER Angularjs2 - preload server configuration before the application starts for Angular to wait rendering any components before the data is available
or you can just use *ngIf to prevent components being rendered before the data is available
<ng-container *ngIf="data">
<child1></child1>
<child2></child2>
</ng-container>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With