【发布时间】:2016-12-28 10:13:20
【问题描述】:
我正在使用带有 @ngrx/store 和效果的 Angular2...我有这样的身份验证效果
@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 请求已成功返回...但如果出现错误显然不会。 p>
如何在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)))
);
【问题讨论】:
-
我可以想到一两种方法来做到这一点,但它们会很老套。最干净的方法(恕我直言)是让
rememberMe字段在 API 响应中返回 - 这对您来说可能吗? -
那肯定是最干净的,但不幸的是我无法控制后端返回的内容..