gpt4 book ai didi

angular - 我如何编写 NgRx 8 Effect 来触发 promise 的 Action

转载 作者:行者123 更新时间:2023-12-04 01:03:48 26 4
gpt4 key购买 nike

我正在努力掌握 NgRx Effects。

使用最新版本,版本 8,我编写了以下效果,它结合了 observable 和 promise,我正在努力掌握如何正确编写它。

这能保证捕捉到所有可能的错误吗?

authLogin$ = createEffect(() => this.actions$.pipe(
ofType(AuthActions.authLogin),
switchMap(async(action) => {
try {
const userState = await this.loginService.login(action.username, action.password);
return AuthActions.authSuccess(userState);
}
catch (error) {
return AuthActions.authLoginError({
error: error
});
}
})
),{ resubscribeOnError: false });

我也不清楚我是否应该使用此配置的最后一位:{ resubscribeOnError: false } 这是否意味着后续执行将创建一个全新的可观察对象?

有没有更好的方法?

最佳答案

我不确定这个 try catch 是否会捕获所有错误,因为我只看到 Promises with .then().catch(),但为什么你不把这个 Promise 转换成 Observable 吗?它会使您的管道更容易编写和正确编写。

使用您的 switchMap 从您的 Promise 中返回一个 Observable

import {from} from 'rxjs';

...
switchMap(action => from(this.loginService.login(action.username, action.password)))
...

之后你可以得到你的 catchError,一个来自 RxJs 的 Observable 操作符。您收到错误和一个名为 caught 的属性,这是可观察的源(来自文档 here)。哪里可以

...
catchError((err, caught$) => {
this.store.dispatch(new AuthActions.authLoginError({ error: error }));
return caught$;
})
...

return caught$ 很重要,因为您可以防止 Effect 在发生错误时死亡。你不需要在 NgRx 8 上那样处理,你可以简单

...
catchError((err, caught$) => {
return of(new AuthActions.authLoginError({ error: error })));
})
...

但是你需要你的 { resubscribeOnError: true } (这是默认值)。如果您不处理错误,此功能会重新订阅您的效果,再次防止它死亡。

然后,在你的 catchError 之后,你可以有一个简单的 map 来返回成功,就像这样

...
map(userState => new AuthActions.authSuccess(userState))

所以,您完成的代码将如下所示

authLogin$ = createEffect(() => this.actions$.pipe(
ofType(AuthActions.authLogin),
switchMap(action => from(this.loginService.login(action.username, action.password))),
catchError((err, caught$) => of(new AuthActions.authLoginError({ error: error })))),
map(userState => new AuthActions.authSuccess(userState))
)); // no resubscribeOnError since default value is true

我认为这是一种更好的方法,因为使用 Observable 进行服务调用,运算符(operator)可以分离职责并让 NgRx 满意。

关于angular - 我如何编写 NgRx 8 Effect 来触发 promise 的 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57549075/

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