angular - How to simplify NgRx effects? Only difference the service method they call-
问题描述
I have got the following code from an NgRx effects file:
registerUser$: Observable<Action> = createEffect(() =>
this.actions$.pipe(
ofType(AuthStoreActions.registerUser),
switchMap(action => {
return this.authService.registerWithEmailAndPassword(action.userCredentials).pipe(
map(() => AuthStoreActions.authSuccess({ navigateTo: "authentication/restaurant" })),
catchError(error => of(AuthStoreActions.setError({ error })))
);
})
)
);
loginUser$: Observable<Action> = createEffect(() =>
this.actions$.pipe(
ofType(AuthStoreActions.loginUser),
switchMap(action => {
return this.authService.loginWithEmailAndPassword(action.userCredentials).pipe(
map(() => AuthStoreActions.authSuccess({ navigateTo: "authentication/restaurant" })),
catchError(error => of(AuthStoreActions.setError({ error })))
);
})
)
);
After the service call both are doing the same thing. How could eleminate the repeatness? I have got an other sibling effects aswell which does more after receiving the response from the server than this example, but apart from the method they call, they are doing the same thing.
解决方案
With the pipe
function, you can bottle up those auth store operators in one.
The power of function composition!
import { pipe } from "rxjs";
const handleAuth = pipe(
map(() => AuthStoreActions.authSuccess({ navigateTo: "authentication/restaurant" })),
catchError(error => of(AuthStoreActions.setError({ error }))));
loginUser$: Observable<Action> = createEffect(() =>
this.actions$.pipe(
ofType(AuthStoreActions.loginUser),
switchMap(action => this.authService.loginWithEmailAndPassword(action.userCredentials).pipe(handleAuth)));
registerUser$: Observable<Action> = createEffect(() =>
this.actions$.pipe(
ofType(AuthStoreActions.registerUser),
switchMap(action => this.authService.registerWithEmailAndPassword(action.userCredentials).pipe(handleAuth)));
推荐阅读
- python - 通过对相同键的值求和来合并字典列表
- c++ - 如何有条件地实例化具有多个模板参数的模板类?
- reactjs - 渲染到带有上下文的字符串?
- java - 我在以下程序中得到 OptionalDataException。为什么会出现这个错误
- android - 如何处理 UI 中的数据库事务延迟以提供良好的用户体验?
- c++ - 将自定义对象添加到向量时如何启用移动语义?
- java - 在 Kafka Consumer 中反序列化 Avro 数据包时出现堆空间问题
- python - python中XGBoost中关于predict_proba函数的问题
- c# - Microsoft graph c# sdk如何将用户分配给应用程序
- scala - 重置与 Url/Port 的连接 - 如果在过去 N 分钟内未收到任何数据