Ngrx 在 http 请求后显示成功或错误消息或重定向的正确方法

Ngrx proper approach on displaying success or error messages or redirects after an http request

我有一个 Ionic 3 应用程序,我在其中使用 ngrx/store and ngrx/effects 来实现副作用或异步操作。一切正常,但有一个小问题。

我应该在调度操作后什么时候调用错误或成功消息。我知道效果工作是根据组件分派的动作分派另一个动作。但是我应该把它放在哪里呢?

下面是我的 reducer.ts

示例
mport { LOGIN_REQUEST, LOGIN_FAILED, LOGIN_SUCCESS } from './../actions/authenticate';
import { AuthState } from './../store';
import { Action } from '@ngrx/store';
import { PostState } from '../store';

const initialState: AuthState = {
    isAuthenticated: false,
    authenticating: false,
    token: null,
    error: null
}

export function authReducer(state = initialState, action: Action) {
    switch (action.type) {
        case LOGIN_REQUEST:
            return {
                ...state,
                authenticating: true,
                // USERS: (<any>action).data.USERS
            }
        case LOGIN_SUCCESS:
            return {
                ...state,
                authenticating: false,
                isAuthenticated: true,
                token: (<any>action).payload.data.token
            }
        case LOGIN_FAILED:
            return {
                ...state,
                authenticating: false,
                error: (<any>action).payload
            }
        default:
            return state;
    }
}

在我的 effects.ts

@Effect()
    authenticate$ = this.actions$.ofType(authActions.LOGIN_REQUEST)
        .pipe(
            switchMap((data: any) => {
                return this.authApi.signIn(data.payload).pipe(
                    map((response: any) => ({ type: authActions.LOGIN_SUCCESS, payload: response })),
                    catchError(error => of({ type: authActions.LOGIN_FAILED, payload: error }))
                )
            })
        )

在我的app.module

imports: [
    ...
    StoreModule.forRoot(rootReducer, { metaReducers }),
    EffectsModule.forRoot(effects),
    StoreDevtoolsModule.instrument({
      maxAge: 5
    })
  ],

最后在我的 component.ts

ionViewWillEnter() {
    this.store.select<any>('auth').subscribe(state => {
      this.auth = state
      if (state.error) this.displayErrorMessage()
    })
  }



    displayErrorMessage() {
    const toast = this.toastCtrl.create({
      message: 'Error occured',
      duration: 3000,
      position: 'top'
    });

    toast.onDidDismiss(() => {
      console.log('Dismissed toast');
    });

    toast.present();
  }

如果你熟悉 redux 你就知道你会理解上面 reducerseffects 中的代码。一切正常,但我认为我的 component 在何时调用成功或错误消息方面存在一个小问题?我应该在效果中调用它吗?但是如何?

如果有人可以帮助提供代码示例,我们将不胜感激。 提前致谢。

您可以将 ActionsSubject 注入组件并监听成功或失败的操作,但我不推荐这样做。

也可以使用效果来显示通知,例如带有 angular material 小吃店:

@Effect({ dispatch: false })
error = this.actions.pipe(
 ofType<ServerError>(ActionTypes.ServerError),
 map(({ payload }) => {
   this.snackBar.open(payload.message, 'Close');
 })
)

有关详细信息,请参阅 Start using ngrx/effects for this