Shared service in Angular2

后端 未结 2 1209
感情败类
感情败类 2021-01-27 18:32

I\'m trying to make a shared service for my app.

import { Injectable } from \'@angular/core\';

@Injectable()
export class SharedService {
  testService() {
            


        
相关标签:
2条回答
  • 2021-01-27 19:05

    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.

    0 讨论(0)
  • 2021-01-27 19:12

    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

    0 讨论(0)
提交回复
热议问题