RxJS/Angular 2/@ngrx/store/effects如何组合动作
我正在使用Angular2和@ngrx/store&effects。。。我有这样的效果RxJS/Angular 2/@ngrx/store/effects如何组合动作,angular,rxjs,Angular,Rxjs,我正在使用Angular2和@ngrx/store&effects。。。我有这样的效果 @Effect() authenticate$ = this.updates$ .whenAction(AuthActions.AUTHENTICATE_REQUEST) .switchMap(update => this.api.post('/authenticate', update.action.payload) // somehow use data in the original
@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
,则在api请求成功返回后,我需要将凭据存储在LocalStorage
服务中。。。但如果有错误,显然不会
在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)))
);
您应该能够
映射可观察的帖子
以包括更新
:
@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)))
)
我可以想出一两种方法来做到这一点,但它们会很粗糙。最干净的方法(IMHO)是在API响应中返回rememberMe
字段-这对您可能吗?这肯定是最干净的方法,但不幸的是,我无法控制后端返回的内容..谢谢@cartant!这就是我想做的!(只需要从.switchMap的末尾删除额外的括号)但这不起作用-switchMap()
的参数需要返回一个Observable,这里不是这样。啊,好吧,我没有仔细看。你说得对,回答很好:+1。不过,对于记录,您可以将((res:any)=>{return{res:res,update:update}}})替换为((res:any)=>({res:res,update:update}))
。请注意,对象文字由括号括起:-)