我正在将我的应用程序迁移到 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 中,因此可以随处使用。没有范围。
有没有办法使用这种方法来实现这种“范围界定”?应该怎么做呢?
在效果中使用管道可能会受到阻碍,但目前在我们的项目中必须保持这种方式。
为了在 Pipe 和 Effect 中使用 Pipe 逻辑时实现正确的作用域,我建议将 Pipe 的逻辑抽象为一个单独的函数。这种方法避免了全局提供 Pipe 的“hacky”方式,并使您的代码更干净、更易于维护。
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;
};
}
// 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);
}
}
// 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 的依赖注入系统。