Reputation: 6009
I was looking into the @ngrx/effects library and they have some example code
@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' }))
);
My question is in the switchMap
call where the author chose to work off of that observable.
Why wouldn't they choose to take advantage of the "flattening" of switchMap
and do something like:
@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' }))
);
Notice how in this refactoring switchMap
just returns the observable from this.http.post()
.
Upvotes: 0
Views: 242
Reputation: 2025
map in both cases yeild the same results, however catch in case 1 will catch errors of only http.post and case 2 will handle errors in any of the observables.
Upvotes: 2