简体   繁体   中英

RXJS Catch operator not catch the Error

I have an issue when I try to set up redux in my Angular4 project, I use the code following to manage the login actions:

@Effect()
  login$: Observable<Action> = this.act
    .ofType(actions.LOGIN)
    .map((action: actions.LoginAction) => action.payload)
    .switchMap((val: { email: string, password: string }) => this.authService.login(val.email, val.password)
      .map(auth => new actions.LoginSuccessAction(auth))
      .catch(err =>  of(new actions.LoginFailAction(err))));

在此处输入图片说明

For some reason Webstorm didn't recognize the rxjs "map" operator but it works well when compile.

And Inside the authService I defined the mock log in check:

login(email: string, password: string): Observable<any> {
    if (email == 'a@gmail.com') {
      return Observable.of('Login Success');
    }
     throw(new Error('Username or password incorrect'));
  }

If the email is a@gmail.com everything works fine and redux state changes however if login fail, my "catch" operator for some reason doesn't catch the error, instead the error appears in the console as following 在此处输入图片说明

In my core module folder I import the module as following:

import 'rxjs/add/operator/catch';

Any one knows what happened here?

Thanks

The problem is that the error in the login method is thrown outside of the observable chain composed in your effect.

That is, the error is thrown instead of returning an observable - to which the map and catch operators would be chained. So it cannot be caught by the catch .

Instead, you could return an observable created with Observable.throw :

import 'rxjs/add/observable/throw';

login(email: string, password: string): Observable<any> {
  if (email == 'a@gmail.com') {
    return Observable.of('Login Success');
  }
  return Observable.throw(new Error('Username or password incorrect'));
}

Doing so will return an observable that will raise an error notification upon subscription. And that error will be caught by your catch .

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