【发布时间】:2017-09-07 22:06:35
【问题描述】:
在 Angular 2+ (4.3.6) 中,我正在使用带有 REST api 的新 HttpClient。 api返回一个json对象,定义如下:
{
count: number,
results: MyObject[]
}
在我的 api 服务中,我有以下函数来检索数据:
public getList(): Observable<ApiResponse> {
return this.http.get<ApiResponse>(url); }
在我的应用程序组件中,我想使用“异步”管道显示数组中对象的数据。因此,我有一个名为 results 的变量
results: Observable<MyObject[]>;
在初始化函数中
ngOnInit() {
this.results = this.myService.getList();
}
最后在模板中
<div *ngFor="let item of results | async">
{{ item.id }}
</div>
我对 Angular 还是很陌生,不知道如何在不创建本地对象的情况下使用异步管道访问结果数组:
temp: MyObject[];
ngOnInit() {
this.temp = this.myService.getList().subscribe(data => this.temp = data.results);
}
有人知道怎么做吗?
【问题讨论】:
-
这就是它或多或少的工作方式。
http request-->observable-->subscription---> 数据
标签: angular typescript observable