Angular 2 Shared Data Service is not working

无人久伴 提交于 2019-12-02 04:02:48
snorkpete

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
})

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!