Search code examples
angularjsangularrxjsobservableangular-directive

Angular 2 Component Interaction via a service


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!


Solution

  • 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?