为什么 @ngrx/effects 使用嵌套的可观察对象

Why would @ngrx/effects use nested observables

我正在查看@ngrx/effects 库,他们有一些示例代码

@Effect() login$ = this.actions$
      // Listen for the 'LOGIN' action
      .ofType('LOGIN')
      // Map the payload into JSON to use as the request body
      .map(action => JSON.stringify(action.payload))
      .switchMap(payload => this.http.post('/auth', payload)
        // If successful, dispatch success action with result
        .map(res => ({ type: 'LOGIN_SUCCESS', payload: res.json() }))
        // If request fails, dispatch failed action
        .catch(() => Observable.of({ type: 'LOGIN_FAILED' }))
      );

我的问题是在 switchMap 调用中,作者选择使用该 observable。

他们为什么不选择利用 switchMap 的 "flattening" 并做类似的事情:

@Effect() login$ = this.actions$
      // Listen for the 'LOGIN' action
      .ofType('LOGIN')
      // Map the payload into JSON to use as the request body
      .map(action => JSON.stringify(action.payload))
      .switchMap(payload => this.http.post('/auth', payload))
        // If successful, dispatch success action with result
      .map(res => ({ type: 'LOGIN_SUCCESS', payload: res.json() }))
        // If request fails, dispatch failed action
      .catch(() => Observable.of({ type: 'LOGIN_FAILED' }))
      );

注意在这个重构中 switchMap 只是 returns 来自 this.http.post() 的观察值。

map 在这两种情况下产生相同的结果,但是 catch 情况 1 将仅捕获 http.post 的错误,而情况 2 将处理任何 observables 中的错误。