在 http 请求中使用 forEach 函数时遇到问题。
我有一个_watchlistElements
变量,包含以下数据:
[{"xid":"DP_049908","name":"t10"},{"xid":"DP_928829","name":"t13"},{"xid":"DP_588690","name":"t14"},{"xid":"DP_891890","name":"t16"},{"xid":"DP_693259","name":"t17"}]
现在,我正在制作一个函数,将从服务器下载每个 xid
的数据。元素:
private download() {
this._watchlistElements.forEach(v =>
this.http.get('http://localhost:8080/getValue/' + v.xid)
.subscribe(res => this._values = res.json()));
}
它必须为每个 v.xid
下载数据作为对象值并将其存储在 _values
中变量。
private _values: Array<WatchlistComponent> = [];
但不知何故, Angular 返回错误 v.xid
元素。它看不到该变量。但这有点奇怪,因为当我在控制台中执行此操作时,我的意思是:将该 json 存储在变量中并在此 v.xid
上使用 forEach 函数元素,一切正常。
ERROR in [default] C:\Users\src\app\appBody\watchlist\watchl ist.component.ts:51:115 Property 'xid' does not exist on type 'WatchlistComponent'.
xid
存在...但在 _watchlistElements
内它异步下载数据...
我不能 100% 确定此方法是否正确,但如果您有任何解决办法,请告诉我。
最佳答案
打印 _values 数组时会发生什么?
上面的错误是类型错误。 WatchlistComponent 界面是什么样的?它包含 xid
属性吗?
您可以通过覆盖类型来解决类型错误,例如...
private download() {
this._watchlistElements.forEach((v as any) =>
this.http.get('http://localhost:8080/getValue/' + v.xid)
.subscribe(res => this._values = res.json()));
}
帮助您更好地构建代码。如果你想组合许多 Observables 的结果,我会使用类似 forkJoin 的东西。
private download():void {
//create an array of Observables
let el$ = _watchlistElements.map(el => {
return this.http.get('http://localhost:8080/getValue/' + el.xid)
.map(res: Response => <any>res.json());
});
//subscribe to all, and store the data, el$ is an array of Observables
Observable.forkJoin(el$).subscribe( data => {
this._values = data; //data will be structured as [res[0], res[1], ...]
});
}
这里是一个使用上述方法工作的 Plunker。 https://plnkr.co/edit/woXUIDa0gc55WJPOZMKh?p=preview
关于javascript - forEach 函数中的 Http 请求。 Angular 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41062395/