简体   繁体   English

RXJS Catch运算符未捕获错误

[英]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: 当我尝试在Angular4项目中设置Redux时遇到问题,我使用以下代码来管理登录操作:

@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. 由于某些原因,Webstorm无法识别rxjs“ map”运算符,但在编译时效果很好。

And Inside the authService I defined the mock log in check: 在authService内部,我在检查中定义了模拟日志:

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 如果电子邮件为a@gmail.com,则一切正常,并且redux状态会更改,但是如果登录失败,则由于某种原因,我的“ catch”运算符无法捕获该错误,而是在控制台中显示以下错误 在此处输入图片说明

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. 问题是login方法中的错误被抛出到效果中可观察到的链之外。

That is, the error is thrown instead of returning an observable - to which the map and catch operators would be chained. 也就是说,将引发错误,而不是返回可观察的对象- mapcatch操作符将被链接到该对象。 So it cannot be caught by the catch . 因此它不能被catch

Instead, you could return an observable created with Observable.throw : 相反,您可以返回使用Observable.throw创建的observable:

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. 这样做将返回一个observable,订阅时将引发错误通知。 And that error will be caught by your catch . 而这个错误将被您catch

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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