如何在无模块方法的 NGRX 效果中使用独立管道

问题描述 投票:0回答:1

我正在将我的应用程序迁移到 Angular 18 并将某些部分转换为独立的。我迁移的第一件事就是 NGRX 商店。

我有StoreModule,它导入了FeatureModules。其中两个使用 SomePipe。

现在我有一个 index.ts,它使用

makeEnvironmentProviders
从功能模块收集所有提供者。

const buildStore = () => makeEnvironmentProviders([
  provideFeature1(),
  provideFeature2(),
...
  makeEnvironmentProviders([
    provideStoreState({ name: 'feature-10', reducer }),
    provideEffects(effects),
  ])
]);

如前所述,某些效果(即服务)依赖于管道(现在是独立的)。当我有模块时,我只需提供/导入管道即可工作。

如果我现在将管道放入我的

makeEnvironmentProviders
之一,它将最终出现在 app.config 中,因此可以随处使用。没有范围。

有没有办法使用这种方法来实现这种“范围界定”?应该怎么做呢?

在效果中使用管道可能会受到阻碍,但目前在我们的项目中必须保持这种方式。

angular ngrx angular18
1个回答
0
投票

为了在 Pipe 和 Effect 中使用 Pipe 逻辑时实现正确的作用域,我建议将 Pipe 的逻辑抽象为一个单独的函数。这种方法避免了全局提供 Pipe 的“hacky”方式,并使您的代码更干净、更易于维护。

分步解决方案

  1. 将管道逻辑提取到函数中:将管道中的逻辑移动到独立函数中。如果逻辑需要注入服务,请使用 Angular 的
    inject
    函数。
// pipe-logic.ts
import { inject } from '@angular/core';
import { SomeService } from './some.service';

export function injectPipeLogicFunc() {
  const someService = inject(SomeService);

  // Write your logic here
  return (value: any, ...args: any[]) => {
    const result = someService.someMethod(value, ...args);
    return result;
  };
}
  1. 使用管道中的函数:修改管道以利用此提取的逻辑。
// your-pipe.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
import { injectPipeLogicFunc } from './pipe-logic';

@Pipe({ name: 'yourPipe' })
export class YourPipe implements PipeTransform {
  private pipeLogic = injectPipeLogicFunc();

  transform(value: any, ...args: any[]): any {
    return this.pipeLogic(value, ...args);
  }
}
  1. 在您的 Effect 中使用该函数:同样,在您的 Effect 中使用该函数以保持一致性。
// some-effect.effect.ts
import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { map } from 'rxjs/operators';
import { someAction } from './actions';
import { injectPipeLogicFunc } from './pipe-logic';

@Injectable()
export class SomeEffect {
  private pipeLogic = injectPipeLogicFunc();

  constructor(private actions$: Actions) {}

  someEffect = createEffect(() =>
    this.actions$.pipe(
      ofType(someAction),
      map(({ payload }) => {
        return this.pipeLogic(payload);
      }),
    )
  );
}

这种方法的好处:

  • 关注点分离:逻辑与管道解耦,使得每个单元都可以独立测试。
  • 重用:您可以在应用程序的不同部分重用该函数。
  • 范围依赖:您可以避免全局提供管道,从而保持范围依赖。

使用此方法,您可以确保您的逻辑保持组织性和可维护性,很好地适合 Angular 的依赖注入系统。


© www.soinside.com 2019 - 2024. All rights reserved.