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))
}
}
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.
you can define Observable in service so that you can subscribe to that Observable from component.
//service
import { Injectable, Inject } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class MyService {
private notify = new Subject<any>();
/**
* Observable string streams
*/
notifyObservable$ = this.notify.asObservable();
constructor(){}
public notifyOther(data: any) {
if (data) {
this.notify.next(data);
}
}
callComponent(value){
this.notify.next({some:value});
}
}
//Component
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { MyService } from './my.service';
export class MyComponent {
private subscription: Subscription;
constructor( private _myService: MyService ){
}
ngOnInit() {
this.subscription = this._myService.notifyObservable$.subscribe((value) => {
console.log(value);
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
import {Subject} from 'rxjs/Subject';
export class MyService {
private invokeEvent = new Subject();
invokeEvent$ = this.missionConfirmedSource.asObservable(); //<<< this is important to declare invokeEvent with asObservable();
callComponent = function(value) {
invokeEvent.next({some:value})
}
}
export class MyComponent {
constructor(private _myService: MyService) {
this._myService
.invokeEvent$ //<<< subscribe to invokeEvent$ to get the result
.subscribe(value => console.log(value))
}
}
来源:https://stackoverflow.com/questions/40393884/angular2-call-a-component-from-a-service