Http request in forEach function. Angular2

眉间皱痕 提交于 2019-12-24 10:19:43

问题


Having problem with using forEach function with http requests.

I have a _watchlistElements variable, which holds following data:

[{"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"}]

Now, Im making a function which will download data from server for each of these xid elements:

private download() {
  this._watchlistElements.forEach(v => 
  this.http.get('http://localhost:8080/getValue/' + v.xid)
  .subscribe(res => this._values = res.json()));
}

It has to download data as object for every v.xid value and store it inside the _values variable.

private _values: Array<WatchlistComponent> = [];

But somehow, angular returns an error with v.xid element. It doesn't see that variable. But it's kinda strange, because when I do it just in console, I mean: store that json inside a variable and use forEach function on this v.xid elements, everything works well.

ERROR in [default] C:\Users\src\app\appBody\watchlist\watchl ist.component.ts:51:115 Property 'xid' does not exist on type 'WatchlistComponent'.

The xid exists... but inside the _watchlistElements which downloads the data asynchonously...

I'm not 100% sure this method is right, but if you have any ideas how to fix it, please tell me.


回答1:


What happens when you print out the _values array?

The error above is a type error. What does the WatchlistComponent interface look like? Does it include an xid property?

You can get around the type error by overriding the type like...

private download() {
  this._watchlistElements.forEach((v as any) => 
  this.http.get('http://localhost:8080/getValue/' + v.xid)
  .subscribe(res => this._values = res.json()));
}

As far as helping you structure your code better. If you want to combine the result of many Observables, I would use something like 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], ...]
  });
}

HERE is a Plunker with the above method working. https://plnkr.co/edit/woXUIDa0gc55WJPOZMKh?p=preview

Related: angular2 rxjs observable forkjoin



来源:https://stackoverflow.com/questions/41062395/http-request-in-foreach-function-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!