Javascript 为什么@ngrx/effects会使用嵌套观测值
我正在查看@ngrx/effects库,它们有一些示例代码Javascript 为什么@ngrx/effects会使用嵌套观测值,javascript,observable,angular5,ngrx-effects,Javascript,Observable,Angular5,Ngrx Effects,我正在查看@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)) .
@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
调用中,作者选择在该调用中处理该可观察对象
为什么他们不选择利用switchMap
的“扁平化”功能来做如下事情:
@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仅从
this.http.post()
返回可观测值,在这两种情况下,map的结果都是相同的,但是案例1中的catch只捕获http.post的错误,案例2将处理任何可观测值中的错误。在这两种情况下,map的结果都是相同的,然而,案例1中的catch将只捕获http.post的错误,而案例2将处理任何可观察对象中的错误