Angular 2 Shared Data Service is not working

后端 未结 2 2013
庸人自扰
庸人自扰 2021-01-25 15:00

I have built a shared data service that\'s designed to hold the users login details which can then be used to display the username on the header, but I cant get it to work.

相关标签:
2条回答
  • 2021-01-25 15:34

    Add it in @NgModule.providers array of your AppModule:

    if you add it in @Component.providers array then you are limiting the scope of SharedDataService instance to that component and its children.

    in other words each component has its own injector which means that headerComponentwill make its own instance of SharedDataServiceand loginComponent will make its own instance.

    0 讨论(0)
  • 2021-01-25 15:45

    This seems to be a recurring problem in understanding Angular's dependency injection.

    The basic issue is in how you are configuring the providers of your service.

    The short version: Always configure your providers at the NgModule level UNLESS you want a separate instance for a specific component. Only then do you add it to the providers array of the component that you want the separate instance of.

    The long version: Angular's new dependency injection system allows for you to have multiple instances of services if you so which (which is in contrast to AngularJS i.e. Angular 1 which ONLY allowed singletons). If you configure the provider for your service at the NgModule level, you'll get a singleton of your service that is shared by all components/services etc. But, if you configure a component to also have a provider, then that component (and all its subcomponents) will get a different instance of the service that they can all share. This option allows for some powerful options if you so require.

    That's the basic model. It, is of course, not quite so simple, but that basic rule of configuring your providers at the NgModule level by default unless you explicitly want a different instance for a specific component will carry you far.

    And when you want to dive deeper, check out the official Angular docs

    Also note that lazy loading complicates this basic rule as well, so again, check the docs.

    EDIT:

    So for your specific situation,

    @Component({
        providers: [SharedDataService]  <--- remove this line from both of your components, and add that line to your NgModule configuration instead
    })
    
    0 讨论(0)
提交回复
热议问题