我可以进行 http 调用来获取响应并访问 block1 中的数据。我无法在 block1 之外使用它。它说未定义。如何在 block1 之外使用响应数据。
this._demoService.get('/app/food.json').subscribe(
data => { //block1
this.foods = data;
console.log(data);
},
err => {
console.log('error '+err.status);
console.log('success');
},
() => console.log('done loading ')
);
//block2
最佳答案
您无法立即访问 this._demoService.get
block 之后的数据,因为您的数据是异步接收的。我的意思是后者,所以当 get
方法返回数据时,数据不存在......
请注意,Angular2 提供了异步管道来帮助处理这种情况。您需要将可观察对象设置为类属性而不是数据。
this.foods = this._demoService.get('/app/food.json');
在模板中您可以使用:
<div *ngFor="let food of foods | async">
{{food.name}}
</div>
关于javascript - 如何在 Angular 2 的类方法中访问ajax数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37789665/