简体   繁体   中英

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. throw new Error() does not work as it just show console error but won't fall to the error callback.

You can create Common method for error handling and call that function from both response and error callback function.

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. I use mergeMap operator for this case :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM