Angular 5+ cannot save result form observable response

落爺英雄遲暮 提交于 2019-12-02 10:34:36

问题


I have an Angular app which consumes data from a webapi. When i make a request then i get an typed observable.

now when i do this:

data: Product[];
productService.getByProductId("061000957").subscribe(res => {
      console.log(res);
      this.data = res;
});
console.log(this.data);

what i see in the console i can see this

I can clearly see, that the result has the Product i need. But why cant i save this to my local variable data?

Thanks


回答1:


Observable is asynchronous just like promise. So console.log(this.data); is executed before the response is returned . Try .

data: Product[];
productService.getByProductId("061000957").subscribe(res => {
       console.log(res);
       this.data = res;
       console.log(this.data);
    });

Now you print your data after it has been set.




回答2:


You are working with async programming you cannot pause the execution of the code and your subscription will be resolved in future but you cannot predict when. console.log() outside the subscribe is executed before your subscription is resolved
what you can do is You can store the value in a class property inside subscribe callback .Refer this for better understanding.

   data: Product[];
productService.getByProductId("061000957").subscribe(res => {
       console.log(res);
       this.data = res;
       console.log(this.data);
    });



回答3:


You should save the data in the HTTP Observable subscription:

productService.getByProductId("061000957").subscribe(res => {
   this.data = res;
   console.log(this.data)   //you can see
})



回答4:


You can do it something like this , finally here will execute after getProductId is complete

productService.getByProductId("061000957")
      .finally(() => console.log(this.data))
      .subscribe(res => {
           console.log(res);
           this.data = res; 
    });

I use do and finally when I try to debug rxjs observable



来源:https://stackoverflow.com/questions/50406767/angular-5-cannot-save-result-form-observable-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!