Search code examples
angulartypescripthttpobservablesubscription

Angular 5+ cannot save result form observable response


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

console screenshot

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

Thanks


Solution

  • 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.