Reputation: 57
I need to load some data in my ngOnInit.
ngOnInit() {
this.perfilService.getPerfisList()
.subscribe(res=> {
this.perfilData = res;
for(var i= 0;i < this.perfilData.length ; i++){
var Indata = {'idUsuario': this.id, 'idPerfil': this.perfilData[i].id };
console.log(Indata);
this.usuarioperfilService.validaUsuariosPerfil(Indata)
.subscribe(res2 => {
this.response = res2;
console.log(res2);
});
}
});
I need to wait for perfilService.getPerfisList
to finish, iterate the response as this.perfilData
and then start to call this.usuarioperfilService.validaUsuariosPerfil
.
The problem is that both functions are being called at the same time so since the request of function 2 is the response of function 1, there's no response yet so the second one is being called with empty request.
How can I manage this during ngOnInit?
Upvotes: 0
Views: 350
Reputation: 9124
Try this:
this.perfilService.getPerfisList().pipe(
switchMap(perfisList => {
const innerObservables = perfisList.map(
perfisItem => this.usuarioperfilService.validaUsuariosPerfil({ 'idUsuario': this.id, 'idPerfil': perfisItem.id }),
);
return forkJoin(innerObservables);
}),
).subscribe(x => console.log(x));
The necessary imports:
import { switchMap } from 'rxjs/operators';
import { forkJoin } from 'rxjs';
Upvotes: 1
Reputation: 3036
You can use RxJs operators map and forkJoin to modify response from one observable to map with another response.
Upvotes: 0