How do I share data between components in Angular 2?

后端 未结 6 624
故里飘歌
故里飘歌 2020-11-22 05:04

In Angular 1.x.x you simply ask for the same service and you end up with the same instance, making it possible to share the data in the service.

Now in Angular 2 I h

6条回答
  •  庸人自扰
    2020-11-22 05:37

    The comment by @maufarinelli deserves its own answer because until I saw it, I was still bashing my head against the wall with this issue even with @Alexander Ermolov's answer.

    The problem is that when you add a providers to your component:

    @Component({
        selector: 'my-selector',
        providers: [MyService],
        template: `
    stuff
    ` })

    This causes a new instance of your service to be injected... rather than being a singleton.

    So remove all instances of your providers: [MyService] in your application except in the module, and it will work!

提交回复
热议问题