当前位置: 动力学知识库 > 问答 > 编程问答 >

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

问题描述:

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); }

);

}

}

网友答案:

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');
  }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: