简体   繁体   English

Angular如何从成功订阅退回到错误?

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

I have this code: 我有以下代码:

  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
    }

The subscription is successful but after checking value I would like to fallback to the error callback so I can do some default handling for either success that does not meet criteria or error with the api call. 订阅成功,但是在检查了值之后,我想回退到错误回调,因此我可以对不满足条件的成功或api调用的错误进行一些默认处理。 throw new Error() does not work as it just show console error but won't fall to the error callback. throw new Error()不起作用,因为它仅显示控制台错误,但不会落到错误回调中。

You can create Common method for error handling and call that function from both response and error callback function. 您可以创建用于错误处理的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.....
}

Once it reach the success function, it will never reach out to your error function, simple because it can't. 一旦达到成功功能,它就永远不会达到您的错误功能,因为它不能成功。 What you should do is check the error in your pipeline , not from the subscribe function. 您应该做的是检查pipeline的错误,而不是通过subscribe函数。 I use mergeMap operator for this case : 在这种情况下,我使用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