繁体   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