How to use inject() in a Pipe with Angular 14?

1.5k Views Asked by At

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!

1

There are 1 best solutions below

4
On

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

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);
    });
  }
}

Example

For More Info