Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 get data before loading child components

Tags:

angular

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;
    });
like image 595
Igor Janković Avatar asked Feb 28 '26 14:02

Igor Janković


1 Answers

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>
like image 109
Günter Zöchbauer Avatar answered Mar 03 '26 02:03

Günter Zöchbauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!