我使用Angular2和@ ngrx / store&效果......我有这样的身份验证效果
@Effect() authenticate$ = this.updates$
.whenAction(AuthActions.AUTHENTICATE_REQUEST)
.switchMap(update => this.api.post('/authenticate', update.action.payload)
// somehow use data in the original `update` to work out if we need to
// store the users credentials after successful api auth call
.map((res:any) => this.authActions.authenticateSuccess(res.json()))
.catch((err:any) => Observable.of(this.authActions.authenticateError(err)))
)
update.action.payload
对象中的rememberMe
标志。所以...如果设置为true
我需要将凭据存储在LocalStorage
服务 AFTER 中,api请求已成功返回...但显然不是,如果有错误。
如何在switchMap
运算符内部实现这一点,我们只能访问api post调用的结果?
以下答案的工作代码
@Effect() authenticate$ = this.updates$
.whenAction(AuthActions.AUTHENTICATE_REQUEST)
.switchMap(update => this.api.post('/authenticate', update.action.payload)
.map((res:any) => {
return {
res: res,
update: update
};
})
.do((result:any) => {
if(result.update.action.payload.remember) {
this.authService.setAuth(result.res.json());
}
})
.map((result:any) => this.authActions.authenticateSuccess(result.res.json()))
.catch((err:any) => Observable.of(this.authActions.authenticateError(err)))
);
答案 0 :(得分:3)
您应该map
post
观察点可以包含update
:
@Effect() authenticate$ = this.updates$
.whenAction(AuthActions.AUTHENTICATE_REQUEST)
.switchMap(update => this.api.post('/authenticate', update.action.payload).map((res:any) => {
return {
res: res,
update: update
};
}))
.do((result:any) => { ... whatever it is you need to do with result.update ... })
.map((result:any) => this.authActions.authenticateSuccess(result.res.json()))
.catch((err:any) => Observable.of(this.authActions.authenticateError(err)))
)