簡體   English   中英

Angular如何從成功訂閱退回到錯誤?

[英]Angular How to fallback to error from successfull subscription?

我有以下代碼:

  this.someService.someFunction(options).subscribe(
    response => {
      if (response === 'xxx') {
        // do something
      } else {
        // fallback to the err callback
      }
    },
    err => {
      // how to get here from above success subscription? 
      console.log(err)
      ...DO SOMETHING IMPORTANT HERE
    }

訂閱成功,但是在檢查了值之后,我想回退到錯誤回調,因此我可以對不滿足條件的成功或api調用的錯誤進行一些默認處理。 throw new Error()不起作用,因為它僅顯示控制台錯誤,但不會落到錯誤回調中。

您可以創建用於錯誤處理的Common方法,然后從響應和錯誤回調函數中調用該函數。

this.someService.someFunction(options).subscribe(
    response => {
      if (response === 'xxx') {
        //Do Something here
      } else {
        //Here err is just temp variable. you can pass anything as per your requirement
        this.handleError(err);
      }
    },
    err => {                 
      this.handleError(err);
    }

//Common method to handle Error
handleError(err){
     //doSomething here.....
}

一旦達到成功功能,它就永遠不會達到您的錯誤功能,因為它不能成功。 您應該做的是檢查pipeline的錯誤,而不是通過subscribe函數。 在這種情況下,我使用mergeMap運算符

this.someService
    .someFunction(options)
    .pipe(mergeMap(x => x == 'xxx' ? of(x): throwError('x is wrong, go to error')))
    .subscribe(...)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM