Angular 2 - Using Shared Service

后端 未结 3 1599
清歌不尽
清歌不尽 2020-11-29 09:36

Looks like shared services is the best practice to solve many situations such as communication among components or as replacement of the old $rootscope concept of angular 1.

3条回答
  •  清歌不尽
    2020-11-29 10:07

    Most of time, you need to define your shared service when bootstrapping your application:

    bootstrap(AppComponent, [ SharedService ]);
    

    and not defining it again within the providers attribute of your components. This way you will have a single instance of the service for the whole application.


    In your case, since OtherComponent is a sub component of your AppComponent one, simply remove the providers attribute like this:

    @Component({
      selector : "other",
      // providers : [SharedService], <----
      template : `
        I'm the other component. The shared data is: {{data}}
      `,
    })
    export class OtherComponent implements OnInit{
      (...)
    }
    

    This way they will shared the same instance of the service for both components. OtherComponent will use the one from the parent component (AppComponent).

    This is because of the "hierarchical injectors" feature of Angular2. For more details, see this question:

    • What's the best way to inject one service into another in angular 2 (Beta)?

提交回复
热议问题