I'm making an API call inside of an ngOnInit
in my component. The API returns an array of type Player
.
Each Player
object has a property Position
. I'm mapping the result of the API call in switchMap
of rxjs, to a component variables called players
.
In the .subscribe
I'm attempting to loop through the result, and .push
the object to another component array, depending on the position
property of player
.
However, each of the position arrays ( goalkeepers
, defenders
, midfielders
, forwards
), are undefined when I try to push
the object.
this.http.get<Player[]>(url)
.pipe(
switchMap(result => {
return this.players = result;
})
)
.subscribe(result => {
for (let i = 0; i < this.players.length; i++) {
if (this.players[i].position == 1) {
this.goalkeepers.push(result[i]);
}
}
}, error => console.error(error));
this.players
and this.goalkeepers
are both of type player[]
.
My understanding here is that the for loop would continue going through each player in this.players, and assigning them to the appropriate position array, but the position arrays are undefined.
In this case the error reads Cannot read property 'push' of undefined
. So my understanding is that the this.goalkeepers
is undefined.
There is no need of switchMap()
, you can set the players
property under a tap()
in the observable. To push data in goalkeepers
you must initialize it first.
this.goalkeepers: Player[] = []
this.http.get<Player[]>(url).pipe(
tap(result => this.player = result)
)
.subscribe(result => {
for (let i = 0; i < this.players.length; i++) {
if (this.players[i].position == 1) {
this.goalkeepers.push(result[i]);
}
}
}, error => console.error(error));
Using tap()
to set players
is useful if you have multiple subscriptions for this.http.get<Player[]>(url)
and you don't want to assign players
individually(which you can do under subcription
itself). If there's only one subscription then assignment under the subscription would be fine.
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.