【问题标题】:Angular 2 - Two Services, second requires result of firstAngular 2 - 两个服务,第二个需要第一个的结果
【发布时间】:2016-05-23 13:37:21
【问题描述】:

我想我需要某种类型的 Promise 链,但语法不知道...

在同一组件内:

我在打电话:

this.somethingService.getSomethings().then(somethings => this.somethings = somethings);

那我需要打电话:

this.otherService.getOthers(this.somethings).then(others => this.others = others);

在第二次服务调用中,我使用第一次的结果对其内容执行聚合函数,但在进行第二次调用时它是空的,因此第二个服务返回空。

如何让第二个服务等到第一个承诺得到解决。

感谢

史蒂夫

【问题讨论】:

    标签: service angular promise chaining


    【解决方案1】:

    你可以这样链接承诺:

    this.somethingService.getSomethings().then(somethings => {
      this.somethings = somethings;
      return this.otherService.getOthers(somethings);
    }).then(others => {
      this.others = others;
    });
    

    第二个回调会收到第一个回调返回的promise结果。

    【讨论】:

    • 感谢您的快速响应,这不会出错 - 但是 this.somethings 是空的???
    • 欧普斯。我的回答中有一个错字:somethings 而不是this.somethings。我更新了...
    • OK 更好,服务二现在返回计算值,但是由于 *ngIf="somethings.length > 0" 我的视图是空的 - 它仍然认为它是一个空数组。
    • 太棒了!所以在第一个回调中添加这个:this.somethings = somethings;。我更新了我的答案...
    猜你喜欢
    • 2018-01-25
    • 1970-01-01
    • 2015-03-16
    • 1970-01-01
    • 2021-05-04
    • 1970-01-01
    • 2019-12-21
    • 1970-01-01
    相关资源
    最近更新 更多