从功能模块 ngrx 更改根状态 属性

Change root state property from feature module ngrx

问题描述 我有一个微调器模块,它是 displayed/hidden 基于我的根状态中的加载 属性。这放在 AppComponent 里面。

export interface AppState {
  loading: boolean
}

我有多个延迟加载的功能模块,每个模块都通过自己的一组效果获取数据。在执行此操作时,我想在效果开始时将 AppState.loading 更新为 true,然后在效果完成时将其设置回 false。

我该怎么做?

解决方法 作为一种解决方法,我在触发我的功能操作之前分派根操作中定义的操作(将加载设置为 true),然后功能效果 returns 一组操作。这些操作之一再次属于根操作(将加载设置为 false)。

service.ts

public getMilestonesAction(q: string) {
  this.store.dispatch(AppActions.loadingAction({ loading: true})); // This belongs to root-actions
  return this.store.dispatch(CalendarActions.getEntriesAction({ q })); // This belongs to feature-actions
}

effect.ts

getMilestonesEffect$ = createEffect(() => this.action$
  .pipe(
    ofType(CalendarActions.getEntriesAction),
    mergeMap(action => this.calendarService.getMilestones(action.q)
    .pipe(
      switchMap((data: Milestone[]) => [AppActions.loadingAction({ loading: false }), CalendarActions.getEntriesSuccessAction({ milestones: data })]),
      catchError((error: any) => from([AppActions.loadingAction({ loading: false }), CalendarActions.getEntriesFailureAction( { error: this.getErrorMessage(error) })]))
    ))
  ));

这是解决这个问题的正确方法吗?

这是正确的,你做对了。

rootfeature 只允许你为需要它们的模块延迟加载 reducer 和 effects,但它们都可以完全访问 store 并可以使用它们需要的操作。

Angular 建议有 core/feature/shared 组模块。在这种情况下,加载动作将在 coreshared,您觉得更合适。