【问题标题】:How to use other Angular11 service inside an ngrx/Store reducer as an initial state?如何在 ngrx/Store reducer 中使用其他 Angular 11 服务作为初始状态?
【发布时间】:2021-04-23 18:25:51
【问题描述】:

reducer 和效果的新功能。基本上,我有这个减速器:

        const realColumnsReducer = createReducer<ColumnsState>(
          toData(AssetsColumns.columnsConfig),//here the service i need to use as a initial state
          on(setColumns, (state, action) => toData(action.columns)),
          on(setSelectedColumns, (state, action) =>
            toData(
              action.columns.map(x => ({
                ...x,
                enabled: true
              }))
            )
          )

这里是我需要使用的 ijectble 服务部分

          columnsConfig: StatefulColumn[] = [
            {
              column: assetCategoryColumn,
              enabled: true
            },
         {
              column: assetCodeColumn,
              enabled: true
            }
        ].map((x, index) => ({ ...x, index, width: columnMinWidthPx } as StatefulColumn));

这里是我的效果

    @Effect()
      applyCompanyPreferences = this.actions$.pipe(
        ofType(applyCompanyPreferences.request),
        switchMap(() => this.store.select(currentIdentity).pipe(onlyTruthy(), take(1))),
        switchMap(identity => from(loadCompanyPreferencesFromIndexedDb(identity))),
        map(x =>
          x
            ? x.columns.map(z => ({ ...this.assetsColumns.columnsConfig[z.index], ...z } as StatefulColumn))
            : this.assetsColumns.columnsConfig
        ),
        mergeMap(x => [setColumns({ columns: x }), applyCompanyPreferences.success({ request: undefined })]),

如何将我的服务用作初始状态?

【问题讨论】:

  • 在不了解你的代码和业务逻辑的情况下,建议你看一下ngrx的官方文档https://ngrx.io/guide/store。正如您在ngrx/redux 流程的第一张图片中看到的那样,您应该只从effects 调用您的服务,而永远不要从您的reducers 调用您的服务。因此,在您的情况下,我建议您执行两个操作:fetchDatafetchDataSuccess,以便您可以在您的效果中调用您的服务fetchDataSuccess 操作,然后更改减速器中的状态。我觉得这有帮助。

标签: angular redux dependency-injection ngrx


【解决方案1】:

据我了解,您希望在第一时间使用该服务来更新状态。 也许这就是你要找的东西:https://ngrx.io/guide/effects/lifecycle#oniniteffects

除此之外,switchMap 和 store.select 的组合是不正确的。本页中的最后一个示例https://ngrx.io/guide/effects 可以让您了解如何正确地做事。

【讨论】:

    猜你喜欢
    • 2016-02-18
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 2021-01-02
    • 2019-07-24
    • 2021-02-09
    • 1970-01-01
    • 2017-12-31
    相关资源
    最近更新 更多