角度2以避免厄运http呼叫的金字塔

时间:2016-10-27 05:54:43

标签: angular typescript

在角度1中我可以嵌套一些http调用并对它们的结果做出如下反应:

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();
});

但在角度2中,我找不到办法做类似的事情......

当我使用subscribe-method时,无法使用另一个订阅方法...

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

有办法解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

只需使用.mergeMap()代替.subscribe()(最后一个除外,因为没有.subscribe()不会进行HTTP调用

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