簡體   English   中英

如何簡化 NgRx 效果? 只是他們調用的服務方法不同——

[英]How to simplify NgRx effects? Only difference the service method they call-

我從 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功能,您可以將那些 auth store 操作員集中在一起。

函數組合的威力!

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM