gpt4 book ai didi

angular - RxJS/Angular 2/@ngrx/store/effects 如何组合 Action

转载 作者:太空狗 更新时间:2023-10-29 18:26:33 24 4
gpt4 key购买 nike

我将 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 `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)))
);

最佳答案

您应该能够映射 post observable 以包含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)))
)

关于angular - RxJS/Angular 2/@ngrx/store/effects 如何组合 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39069724/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com