Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 executing method after http.get from another component has finished

Tags:

angular

I have a service called JwtService. This service has a method to get the user data. I call this method in my component:

this.JwtService.getUserData();

Now, whenever I click a button in my component - I call this method. After this method is called, I call another local method:

this.updateMoves();

which works on the data in the JwtService service.

The problem is that this.JwtService.getUserData(); is not finished executing and update the new data, and this.updateMoves(); executed on the old data.

Unwanted solution: Moving the updateMoves() method to the service and call it after the response is received can make it work, but since this method belong to specific one component, I don't wanna do that.

Unwanted solution 2: new service variable IS_LOADED and check in my component if it has finished loading. It causes some problems in my app.

Any other solution that might work to run updateMoves() after service data has received?

My getUserData() method:

getUserData()
    {
        this.good = false;
    if (this.getToken()) {
    this.http.get('user/info?token='+this.getToken())
      .map((res:Response) => res.json())
      .subscribe(
        data => {
            this.userData = data.user;
            this.LOADED = true; 
        },
        err => { this.checkToken(err); }
      );
    }
}
like image 944
TheUnreal Avatar asked May 04 '26 20:05

TheUnreal


1 Answers

If your getUserData method returns an observable, you could subscribe on it and execute the second method in the associated callback:

this.JwtService.getUserData().subscribe(() => {
  this.updateMoves();
});

Edit

You could use the do and catch operators:

getUserData() {
  this.good = false;
  if (this.getToken()) {
    return this.http.get('user/info?token='+this.getToken())
      .map((res:Response) => res.json())
      .do(
        data => {
          this.userData = data.user;
          this.LOADED = true; 
      })
      .catch(
        err => { this.checkToken(err); }
    );
  } else {
    return Observable.throw('Not good');
  }
}
like image 180
Thierry Templier Avatar answered May 06 '26 10:05

Thierry Templier