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...
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.
HERE is a Plunker with the above method working. https://plnkr.co/edit/woXUIDa0gc55WJPOZMKh?p=preview
Related: angular2 rxjs observable forkjoin