Как упростить эффекты NgRx? Единственная разница в методе обслуживания, который они называют - PullRequest
1 голос
/ 31 января 2020

Я получил следующий код из файла эффектов 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 })))
        );
      })
    )
  );

После вызова службы оба делают одно и то же. Как можно устранить повторение? У меня есть и другие родственные эффекты, которые делают больше после получения ответа от сервера, чем в этом примере, но кроме метода, который они вызывают, они делают то же самое.

Ответы [ 2 ]

2 голосов
/ 31 января 2020

С помощью функции pipe вы можете bottle до тех операторов хранилища аутентификации в одном.

Сила композиции функций!

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)));
0 голосов
/ 01 февраля 2020

Я бы сказал, оставьте это как есть, вместо этого, желая уменьшить некоторое значение LO C

Решение «как есть» более читабельно и легче реагирует на изменения по сравнению со следующим:

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