How to throw error from RxJS map operator (angular)

后端 未结 3 669
悲哀的现实
悲哀的现实 2020-12-02 16:02

I want to throw an error from my observable\'s map operator based on a condition. For instance if correct API data is not received. Please see the following

3条回答
  •  青春惊慌失措
    2020-12-02 16:42

    If you feel like throw new Error() seems un-observable-like you can use return throwError(...) with switchMap instead of map (the difference being switchMap has to return a new observable instead of a raw value):

    // this is the import needed for throwError()
    import { throwError } from 'rxjs';
    
    
    // RxJS 6+ syntax
    this.httpPost.pipe(switchMap(res => { 
       if (res.bearerToken) {
          return of(this.saveJwt(res.bearerToken)); 
       } 
       else {
          return throwError('Valid token not returned');  // this is 
       }
    });
    

    or more concisely:

    this.httpPost.pipe(switchMap(res => (res.bearerToken) ? 
                                        of(this.saveJwt(res.bearerToken)) : 
                                        throwError('Valid token not returned')
    ));
    

    The behavior will be the same, it's just different syntax.

    You're literally saying 'switch' from the http observable in the pipe to a different observable, which is either just 'wrapping' the output value, or a new 'error' observable.

    Don't forget to put of or you'll get some confusing error messages.

    Also the beauty of 'switchMap' is that you can return a whole new 'chain' of commands if you wanted to - for whatever logic needs to be done with saveJwt.

提交回复
热议问题