Angular2 - Share data between components using services

前端 未结 3 1802
灰色年华
灰色年华 2020-11-29 06:20

I have an object that I want to share between my components into an Angular2 app.

Here is the source of the first component:

/* app.component.ts */

         


        
相关标签:
3条回答
  • 2020-11-29 07:13

    For the latest version of angular, if you want to share the service, you can't add it to the bootstrap function. Just add it to the NgModule providers list as you would do with a normal service, its default behaviour will be singleton.

    bootstrap(AppComponent);

    @NgModule({
        declarations: [
            ....
        ],
        imports: [
           ....     
        ],
        providers: [
            ConfigService,
    ....
    
    0 讨论(0)
  • 2020-11-29 07:15

    Don't add ConfigService to providers of your component. This results in new instances for every component. Add it to providers of a common parent component. If you add it to your root component or bootstrap(App, [ConfigService]) your entire application shares a single instance.

    0 讨论(0)
  • 2020-11-29 07:21

    You define it within your two components. So the service isn't shared. You have one instance for the AppComponent component and another one for the Grid component.

    @Component({
      selector: 'my-app',
      templateUrl: 'app/templates/app.html',
      directives: [Grid],
      providers: [ConfigService]
    })
    export class AppComponent {
      (...)
    }
    

    The quick solution is to remove the providers attribute to your Grid component... This way the service instance will be shared by the AppComponent and its children components.

    The other solution is to register the corresponding provider within the bootstrap function. In this case, the instance will be shared by the whole application.

    bootstrap(AppComponent, [ ConfigService ]);
    

    To understand why you need to do that, you need to be aware of the "hierarchical injectors" feature of Angular2. Following links could be useful:

    • What's the best way to inject one service into another in angular 2 (Beta)?
    • https://angular.io/docs/ts/latest/guide/hierarchical-dependency-injection.html
    0 讨论(0)
提交回复
热议问题