在完成所有http调用后,angular 2执行某些操作

时间:2017-07-20 08:36:20

标签: javascript angular observable

我在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 => {

        });

2 个答案:

答案 0 :(得分:0)

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

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

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

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

    });

答案 1 :(得分:0)

你可以使用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');
  }
});