如何简化NgRx效果?只是区别于他们调用的服务方法-



我从NgRx效果文件中获得了以下代码:

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 })))
);
})
)
);

在服务呼叫之后,两者都在做同样的事情。如何消除重复性? 我还有一个其他兄弟效应,它在收到来自服务器的响应后比此示例做得更多,但除了他们调用的方法之外,他们还在做同样的事情。

使用pipe功能,您可以将这些身份验证存储操作员合二为一。

功能组合的力量!

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)));

我会说,保持它,而不是想要减少一些LOC

与以下解决方案相比,原样解决方案更具可读性,并且更容易对更改做出反应:

loginUser$: Observable<Action> = createEffect(() =>
this.actions$.pipe(
ofType(AuthStoreActions.loginUser, AuthStoreActions.registerUser),
switchMap(action => {
return this.authService[action.serviceMethod](action.userCredentials).pipe(
map(() => AuthStoreActions.authSuccess({ navigateTo: "authentication/restaurant" })),
catchError(error => of(AuthStoreActions.setError({ error })))
);
})
)
);

相关内容

  • 没有找到相关文章

最新更新