I have a global service. in this global service, I'm making an important API call to get the user data. This user data API call is important to many pages in my website, and therefore need to be executed first of all. I placed this API call in my service constructor this way:
constructor(public router: Router,private http: Http) {
if (this.getToken())
this.getUserData().subscribe(() =>{});
else
this.LOADED = true;
}
which works fine.
Now let's talk about a component. I have a component named WorldComponent
which uses the info received from the this.getUserData()
method which is executed in the service constructor, as shown above.
When I'm trying to use the data I receive from the service API call, I get an error that this data don't exists (because the API call hasn't finished yet when I call this component). Therefore I placed in my component OnInit() method the following code:
ngOnInit()
{
this.service.getUserData().subscribe(() => {
if (this.service.userData.fly)
this.router.navigate(['fly']);
if (this.service.userData.ride)
this.router.navigate(['ride']);
this.loaded = true;
});
}
When using the cove above, my component works great, but if you will notice - the API call will be executed **twice!*.
Is there any way to wait for the API call to load before using this component, of even better, any of the components in my app?
Befoer RC.5 I could *ngIf
the router outlet and the router worked only when the data is received. Now I can't place *ngIf outside router outlet, and I need to find another solution.