2

I have two parallel directives (as apposed to parent-child) and I want them to communicate via a service using observable if possible. I've read the official component interaction guidline, but it talks about parent-child interaction. I tried to make a plunker with two directives but it doesn't work.

Basically, what I want is to create a service:

export class DirService {
   contentSource = new Subject();
   content$ = this.contentSource.asObservable();
}

And then, use this service to make a bridge between < dir1 > and < dir2 >. Could someone point out how to implement this senerio?

Btw, I choose to use observable mainly because:

  • I read the post in this thread.
  • If I want many directives to communicate, I guess observable could make the logic more clear.

Thanks!

Community
  • 1
  • 1
lys1030
  • 283
  • 1
  • 5
  • 17

2 Answers2

5

If you add the "shared" service to providers of each component

@Component({
    selector: 'dir2',
    template: '{{field}}',
    providers: [DirService]
})

then for each component a new instance is maintained.

To get a shared service you either add it only in bootstrap(AppComponent, [DirService]) or one common ancestor of the components and directives that defines the root component and the scope of the shared service.
This way every descendant gets the same instance.

Plunker example

See also
- AngularJs 2 - multiple instance of service created
- How to use Dependency Injection (DI) correctly in Angular2?

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
1

You need to specify the DirService service when bootstrapping your application:

bootstrap(AppComponent, [ DirService ]);

And remove it from component providers attribute:

@Component({
  (...)
  //providers: [ DirService ]
})

This way you will share the same instance of the service for the whole application (and both components).

See this plunkr: http://plnkr.co/edit/rYq3iicbd4mKGyxHlJmg?p=preview.

This behavior is linked to the "hierarchical injectors" of Angular2 dependency injection.

For more details, you could have a look at this question:

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360