Tobias Koller Tobias Koller - 1 month ago 13
TypeScript Question

angular 2 to avoid pyramid of doom http calls

in angular 1 I could nest some http-calls and react on their result like this:

this.$qSessionPromise
.then(() => {
return this.Init();
})
.then(() => {
return this.Services.GetData1("id1");
})
.then((data: model.DataType1) => {
this.data = data;
})
.then(() => {
this.SetIsInitialized(true);
this.handler = new MyHandler(this.data);
this.RegisterEvents();
});


but in angular 2 I couldn't find a way to do something similar...

when I use the subscribe-method there is no way to ad another subscribe-method...

this.service.GetData1()
.subscribe(data:model.DataType1 => {
this.data = data;
return this.Services.GetData2("id2");
})
.subscribe(data:model.DataType2 => {
this.data = data;
})


is there a way to handle this?

Answer

Just use .mergeMap() instead of .subscribe() (except on the last one because without .subscribe() no HTTP call will be made

   this.service.GetData1()
   .mergeMap(data:model.DataType1 => {
       this.data = data;
       return this.Services.GetData2("id2");
   })
   .subscribe(data:model.DataType2 => {
       this.data = data;
   })
Comments