Angular 5+ 无法保存可观察响应的结果

Angular 5+ cannot save result form observable response

我有一个 Angular 应用程序,它使用来自 webapi 的数据。 当我发出请求时,我得到一个类型化的可观察对象。

现在当我这样做时:

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

我在控制台看到的我可以看到这个

我可以清楚地看到,结果是我需要的产品。 但为什么我不能将其保存到我的本地变量数据中?

谢谢

Observable 和 promise 一样是异步的。所以 console.log(this.data); 在返回响应之前执行。尝试。

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

设置好后打印数据。

您正在使用 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 以便更好地理解。

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

您应该将数据保存在 HTTP Observable 订阅中:

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

你可以这样做,最后这里会在getProductId完成后执行

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

当我尝试调试 rxjs observable

时,我使用 do 和 finally