Shared service in Angular2

岁酱吖の 提交于 2019-12-02 21:47:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!