问题
I'm trying to make a shared service for my app.
import { Injectable } from '@angular/core';
@Injectable()
export class SharedService {
testService() {
console.log('share!');
}
}
Then I inject it in my app.component's providers but when I tried to call it in the constructor of a child component like this: constructor(public sharedService: SharedService) {} I've got an error:
Can't resolve all parameters for MyComponent. I also tried to inject it in my app.module providers and also got this error. What should I do? How to inject it properly? Can anyone provide an example of proper shared service for antire app(it has several modules)?
I have routing sistem and I want to have a shared service and change it's data from the component which module is currently represented.
回答1:
I believe you use latest version and want to use singleton service.
For that you have to register your service in @NgModule({}) as shown here,
import {Sharedservice} from 'valid path';
@NgModule({
imports:[BroswerModule],
...
providers:[SharedService]
})
Now, In child and parent component just import Sharedservice at the top of the file.
NOTE : Remove providers:[SharedService] from each component.
回答2:
You need to set who's the provider for that service with providers keyword in @Component or @NgModule annotation. This is well documented already zilion times, see:
https://angular.io/docs/ts/latest/guide/dependency-injection.html#!#injector-providers
https://angular.io/docs/ts/latest/guide/ngmodule.html#!#providers
https://angular.io/docs/ts/latest/cookbook/component-communication.html
https://angular.io/docs/ts/latest/cookbook/dependency-injection.html
来源:https://stackoverflow.com/questions/39958238/shared-service-in-angular2