Reputation: 571
I am commmunicating between two components using a service and the Subject from rxjs. But subsequent next() calls on the Subject does not invoke the function that I have called in the subscribe() method of my compoent.
In the code below, only the first call of component2 's methodToSendMessage(), invokes the doSomething() of Component1. Any subsequent invocations of methodToSendMessage() just does not trigger the doSomething() method.
Can anyone please help me on why this is happening ?
Component 1 is as follows
export class Component1 implements OnInit {
constructor(someService: SomeService) {
}
ngOnInit() {
someService.showMessage()
.subscribe( msg => {
doSomething();
})
}
doSomething(){
//the problem is this function gets called only once.
}
}
Component 2 is as follows
export class Component2 implements OnInit {
constructor(someService: SomeService) {
}
methodToSendMessage() {
this.someService.notify(JSON.parse(""));
}
}
And my service is as follows
@Injectable()
export class SomeService{
public subject= new Subject<JSON>();
public notify(res: JSON) {
this.subject.next(res);
}
public showMessage(): Observable<JSON> {
return this.subject.asObservable();
}
}
Upvotes: 0
Views: 3423
Reputation: 2486
Try subscribing to the subject directly
So component1 will look like
export class Component1 implements OnInit {
constructor(someService: SomeService) {
}
ngOnInit() {
someService.subject
.subscribe( msg => {
doSomething();
})
}
doSomething(){
//the problem is this function gets called only once.
}
}
and your service will be
@Injectable()
export class SomeService{
public subject:Subject<any> = new Subject<JSON>();
public notify(res: JSON) {
this.subject.next(res);
}
}
Upvotes: 0