【问题标题】:angular 2 do something after all http calls finishedangular 2 在所有 http 调用完成后做一些事情
【发布时间】:2017-07-20 08:36:20
【问题描述】:

我在 angular 2 组件中执行 2 个 http 调用。我想在这两个服务调用完成后显示成功消息。我该怎么做?

this._cashierService.postCharge(this.postCharge).subscribe( resPostCharge => {

          this.footerNotification.success('Save', 'Successfully saved'); //i want to show this after 2 calls finished
        }, errorMessage => {

        });

this._cashierService.splitCharge(this.postCharge).subscribe( resPostCharge => {

          this.footerNotification.success('Save', 'Successfully saved');
        }, errorMessage => {

        });

【问题讨论】:

  • 使用 fork-join 框架来做到这一点。

标签: javascript angular observable


【解决方案1】:

链接可观察对象,以便它可以一个一个调用并在最后一个打印控制台。从第一个观察者订阅返回第二个调用。

this._cashierService.postCharge(this.postCharge)
    .subscribe(resPostCharge => {

        return this._cashierService.splitCharge(this.postCharge);
    }, errorMessage => {

    })
    .subscribe(resPostCharge => {
        this.footerNotification.success('Save', 'Successfully saved');
    }, errorMessage => {

    });

【讨论】:

  • 这是最好的方法吗?
  • 内部调用将在第一次调用完成后运行。这将失去异步性。
  • 是的。如果你有多个 req 使用链机制
  • @sachila ranawaka 不,链机制不是要走的路。使用 fork-join 并行执行调用并等待它完成,然后再对结果进行操作。
【解决方案2】:

您可以使用 2 个变量来解决该问题:

let firstCallfinished = false;
let secondCallfinished = false;

this._cashierService.postCharge(this.postCharge).subscribe(() => {
  firstCallfinished = true;
  if (secondCallfinished) {
    this.footerNotification.success('Save', 'Successfully saved');
  }
});

this._cashierService.splitCharge(this.postCharge).subscribe(() => {
  secondCallfinished = true;
  if (firstCallfinished) {
    this.footerNotification.success('Save', 'Successfully saved');
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 2011-10-09
    • 1970-01-01
    相关资源
    最近更新 更多