首页 > 解决方案 > 从功能模块 ngrx 更改根状态属性

问题描述

问题描述 我有一个微调模块,它根据我的根状态下的加载属性显示/隐藏。这是放置在 AppComponent 中的。

export interface AppState {
  loading: boolean
}

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

我该怎么做呢?

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

服务.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
}

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

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

标签: angularngrx

解决方案


这是正确的,你做对了。

root并且feature只允许您为需要它们的模块延迟加载减速器和效果,但它们都可以完全访问存储并且可以使用它们需要的操作。

Angular 建议使用core/feature/shared模块组。在这种情况下,加载动作将在coreshared中,您认为更合适。


推荐阅读