简体   繁体   中英

Shared service in Angular2

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM