Rob Rob - 1 month ago 8
Javascript Question

Angular2 call a Component from a Service

I am trying to call a Method in my

Component
from a a
Service
. What is the proper way to do this? I have tried to use
rxjs Subject
to create an Observable, but I cannot get it to fire.

import {Subject} from 'rxjs/Subject';
export class MyService {
callComponent = function(value) {

let invokeEvent = new Subject();

invokeEvent.next({some:value})
}
}


and in my Component

export class MyComponent {
constructor(private _myService: MyService) {
this._myService.invokeEvent.subscribe(value => console.log(value))
}

}

Answer

Here's the plunker: http://plnkr.co/edit/WKSurRJMXo5JZOPrwSP5?p=preview

Change your service like this

import {Subject} from 'rxjs/Subject';

@Injectable()
export class MyService {

    invokeEvent:Subject<any> = new Subject();


    callComponent(value) {
        this.invokeEvent.next({some:value})
    }
}

Don't forget to provide it in your component

@Component({
  selector: 'my-component',
  template: `
  `,
  providers: [MyService]
})
export class MyComponent {
       constructor(private _myService: MyService) {
         this._myService.invokeEvent.subscribe(value => console.log(value));
         setTimeout(()=>{
            this._myService.callComponent(1);
         },1000);
       }
}

Also, If you want this service to be a global shared service; put(provide) it in your bootstrap(old) or ngModule so it will share the same singleton instance throughout your app.