No provider for service in pipe

3.3k views Asked by At

I have a custom pipe and a directive that I would like to share some data between. I created a service, that should be handling this. I get the following error:

Error: No provider for MyService

Here's the code:

@Injectable()
export class MyService {
    private data: any;
    get Data():any {
        return this.data;
    }
    set Data(d: any) {
        this.data = d;
    } 
}

The directive should provide the service:

@Directive({
     selector: '[my-directive]',
     providers: [MyService],
})
export class MyDirective {
    constructor(private serv: MyService) {}
}

The pipe should get the service as well, when used on the same component:

@Pipe({
    name: 'myPipe'
})
export class MyPipe {
    constructor(private serv: MyService) {}
    transform(value: any) {
        return value + 'foo';
    }
}

This is used for example on an input like this:

<input [value]="text | myPipe" my-directive />

After I read the angular2 docs on DI, and searched on this topic, I could not find anything that I did wrong. As far as I know this should work. Any ideas why does not?

ps: Using angular 2.x with Ionic2

2

There are 2 answers

2
Julia Passynkova On

Try to add the providers array to a component that has this directive with pipe. I think it should work.

1
Jorawar Singh On

You can declare your service in ngModule.providers and later just inject in your constructor whete ever you want to use it. If Your service is part of another module then you have to import that module. Once you have the service in provider the later you don't need to declare in provider in your pipe or directive.

Id you want new instance in every component or pipe you use this service then do not make this part of ngModule.providers but then you have to declare it in every pipe or directive's provider.