我正在尝试将服务离子注入管道。通常,inject(...)
工作得很好,但在管道上下文中,我得到了错误:
Error: NG0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with `EnvironmentInjector#runInContext`
我做错了什么,或者我该如何让它发挥作用?
当我把依赖项放在构造函数中时,服务工作得很好,比如constructor(private service: CheckboxFilterPipe)
,但我现在想在组件代码中使用它(以编程方式使用transform()
(,再也不能在构造函数中写入依赖项了。
@Pipe({
name: 'checkboxFilter',
pure: true,
})
export class CheckboxFilterPipe implements PipeTransform {
/** */
private service = inject(CheckboxFilterService);
constructor() {}
transform(items: Array<any>, filter: IFilterSettings, defaultFilter?: IFilterDefaults): any {
this.service.init();
return this.service.doFilter(items, filter, defaultFilter);
}
}
谢谢你的帮助!
如果您使用的是Angular 14.1版本。您可以使用runInContext API。这将允许您调用注入内部函数体
管道.ts
import {
EnvironmentInjector,
inject,
Pipe,
PipeTransform,
} from '@angular/core';
import { UtilServiceService } from './util-service.service';
@Pipe({
name: 'demo',
})
export class DemoPipe implements PipeTransform {
private environment = inject(EnvironmentInjector);
transform(value: any, args?: any): any {
return this.environment.runInContext(() => {
return inject(UtilServiceService).filterData(value);
});
}
}
示例
了解更多信息