检查可观察是否完整

问题描述 投票:3回答:3

我需要在一个observable完成之后显示一个toast,我怎么做,我的代码是:

this.commerceCtrl.UpdateCategories(this.toSave).subscribe(data => {
  }, error => {
    this.mainFunction.showError(error)
  }),
  complete => {
    this.mainFunction.showToast(this.localization.message_ok)
  }

我试着这样做:

this.commerceCtrl.UpdateCategories(this.toSave).subscribe(data => {
  }, error => {
    this.mainFunction.showError(error)
  }),
  () => {
    this.mainFunction.showToast(this.localization.message_ok)
  }

但它不起作用

javascript angular typescript rxjs observable
3个回答
6
投票

你必须传递complete处理程序作为订阅的第三个参数。

在您的代码中,只需将右括号移到最后。

更改此代码:

this.commerceCtrl.UpdateCategories(this.toSave).subscribe(data => {
  }, error => {
    this.mainFunction.showError(error)
  }), // <===== Remove this parenthesis
  () => {
    this.mainFunction.showToast(this.localization.message_ok)
  }; // <====== It should be here

对此:

this.commerceCtrl.UpdateCategories(this.toSave).subscribe(
  data => {
    // next handler body
  }, error => {
    this.mainFunction.showError(error)
  }, () => {
    this.mainFunction.showToast(this.localization.message_ok)
  }
);

2
投票

您可以将对象参数赋予subscribe()函数:

this.commerceCtrl.UpdateCategories(this.toSave).subscribe({
   next: value => { ... },
   error: err => { ... },
   complete: () => { ... }
});

0
投票

您可以尝试使用finally方法

this.commerceCtrl.UpdateCategories(this.toSave).finally(() => {
    // complete
}).subscribe((data) => {
    // success
}, (error) => {
    // error
});

资料来源:https://github.com/angular/angular/issues/7865#issuecomment-204408637

© www.soinside.com 2019 - 2024. All rights reserved.