K.Rice
K.Rice

Reputation: 609

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.

Upvotes: 0

Views: 4409

Answers (2)

micronyks
micronyks

Reputation: 55443

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.

Upvotes: 4

Related Questions