I'm trying to ion inject a service into a pipe. Usually, inject(...)
works fine, but in a pipe context I'm getting the error:
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`
What I'm doing wrong or how can I get it to work?
The service works fine when I put the dependency in the constructor, like constructor(private service: CheckboxFilterPipe)
, but I want to use it now in the component code (using transform()
programmatically), it's no option to write the dependency in the constructor anymore.
@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);
}
}
Thank you for your help!
If you are using Angular 14.1 version. you can use runInContext API. which will allow you to call inject inside function body
pipe.ts
Example
For More Info