Angular 5+无法保存结果表可观察到的响应 [英] Angular 5+ cannot save result form observable response

查看:65
本文介绍了Angular 5+无法保存结果表可观察到的响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Angular应用程序,该应用程序使用来自webapi的数据. 当我发出请求时,我得到的是可观察的类型.

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

现在,当我这样做时:

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?

谢谢

推荐答案

Observable与Promise一样是异步的.因此,在返回响应之前执行console.log(this.data);.试试吧.

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.

这篇关于Angular 5+无法保存结果表可观察到的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆