简体   繁体   中英

Http request in forEach function. Angular2

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM