Angular 2 – Make sure one API call has made before making others

On every page of my website, once the user is logged in, I get the user data.

This single API call, is the most important one in my app.

The information I get from this API call is used in many components all over my application, and I need to make sure that my template will “wait” for this API call before moving on and showing my application data.

This API Call is defined in a service constructor, and this is how this method look like in my service:

public userData;
...
    getUserData()
        {
        if (this.getToken()) {
        console.log("Getting user..");
        this.http.get('thisUser?token='+this.getToken())
          .map((res:Response) => res.json())
          .subscribe(
            data => {
                this.userData = data.user;
            },
            err => { this.checkToken(err); }
          );
        }

Which means that my JwtService.userData variable must get information before showing my template (I have used *ngIf="JwtService.userData in my components).

How I can make sure I got this data first of all?

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

It depends on architecture of you application.

You can make your application lightweight with template like <div #child><div/>. Implement lifecycle listener OnInit and do any checks you want in ngOnInit method, then load your main component with DynamicComponentLoader: dcl.loadAsRoot(MainComponent, '#child', injector);.

Jason
Guest

The question is interesting.

I don’t know if my solution is going to work well because I am writing from my smartphone and I can’t test my code.

You are probably using a router, so you have somewhere a <router-output>.

You could try to write something like this:

<div ngIf="(callDone | async)">
 <router-output></router-output>
</div>

Where callDone is an Observable that is set to false before the API call and set to true in the callback.

Another possibility could be to link all the components to the Observable callDone. The Angular change detector should do all the work