In v15 I bootstrap the app component using bootstrapApplication
.
Inside the ts
I import AppHeaderComponent
and write it in imports
section.
The AppHeaderComponent
inject foo = inject(FooService);
.
The FooService
is inject BazPipe
.
BazPipe
is contain the following pipe (with standalone is true):
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'baz',
standalone: true,
})
export class BazPipe implements PipeTransform {
constructor() {}
transform(value) {
return value;
}
}
Why angular throw error in the console?
ERROR
Error: R3InjectorError(Environment Injector)[FooService -> BazPipe -> BazPipe]:
NullInjectorError: No provider for BazPipe!
CodePudding user response:
If you want to resolve pipe using dependency injection you need to provide BazPipe as provider in root component
bootstrapApplication(AppComponent,{ providers:[BazPipe]});
CodePudding user response:
You cannot use pipe
as injectable
service class. Pipe
is like the component class, should be used directly in place and does not participate in DI. But you can do this for use pipe
everywhere in code with a static method:
@Pipe({
name: 'baz',
standalone: true,
})
export class BazPipe implements PipeTransform {
static transform(value) {
return value;
}
transform(value) {
return BazPipe.transform(value);
}
}
CodePudding user response:
You CAN use pipe in DI, you just need to provide them in module, but I wouldn't suggest you that because there are big issue with pipe providers: they can't be providedIn: 'root'
. Why is this a problem, if you could just provide the pipe in your root module? Well, after you providing something manually in root module this thing will not be tree-shacked and will be always in your main.js bundle.
So there are 2 possible solutions:
- Create static method in your pipe and use this static method where you need in your code (as was mentioned by Anton Marinenko).
- Move pipe logic to a service and use this service in components and other services.
I should also mention that I have faced the same problem with Angular CurrencyPipe
which I wanted to use in my service that is providedIn: 'root'
since CurrencyPipe
has no static method or service I've ended up providing this pipe in my app.module.
CodePudding user response:
You can simply add @Injectable({ providedIn: 'root' })
to the pipe and use it as a service.