2

In looking through a couple of ngrx examples (https://github.com/SekibOmazic/ngrx-auth-example) and (https://github.com/ngrx/angular2-store-example) they both create a subscription to the store, and then make REST API calls.

I've modified both of their code to return errors and yet the subscriptions remain in tact (e.g. returning a 404 when trying to login). I can see the error in the console yet I can login again.

In my code, I have a nearly identical setup, yet a failed login response kills my subscription (as near as I can tell).

What magic do I need in order for a 4XX error response codes to not kill my subscription?

private actions$ = new BehaviorSubject<Action>({ type: actions.INIT, payload: null })

constructor(
  public http: Http,
  private store: Store<AppStore>
) {
  let logins = this.actions$
    .filter(action => { debug('ACTION', action); return action.type === actions.LOGIN_USER })
    .do(() => { debug('DISPATCH'); this.store.dispatch({ type: actions.LOGIN_REQUEST }) })
    .mergeMap(action => this.http.post('/auth/login', JSON.stringify(action.payload)))
    .share();

  let loginSuccess$ = logins
    .filter((payload: IResponse) => payload.data.token !== null)
    .map((payload: IResponse) => ({ type: actions.USER_AUTHENTICATED, payload: payload.data }));

  let loginFailure$ = logins
    .filter((payload: IResponse) => payload.data.token === null)
    .map((payload: IResponse) => ({ type: actions.LOGIN_FAILURE, payload: payload.data }));

  Observable
    .merge(loginSuccess$, loginFailure$)
    .subscribe((action: Action) => this.store.dispatch(action))
}

login(payload: ILogin) {
  this.actions$.next({ type: actions.LOGIN_USER, payload });
}
4

1 回答 1

3

这更多地与 RxJS 本身有关,而不是与 ngrx 的任何事情有关。错误将结束流,除非您 a) 在 .subscribe(next, err) 处理程序中处理它,或使用 .catch() 运算符或类似操作。

例如

let loginFailures$ = http.get('failurl')
  .map(res => res.json())
  //handle error with catch
  .catch(err => {
    //return a 'fixed' observable
    return Observable.of({ type: actions.LOGIN_FAILURE, payload: err })
  })
  .subscribe(action => store.dispatch(action));
于 2016-02-24T01:27:37.360 回答