I want to send message from ComponentA to ComponentB. And I am using service for that. Here is the code- My problem is if I call sendInfoToB() from componentA's html file (event hooked to a button click), then I'm recieving the message in componentB /getting console.log(this.check); and console.log(message); 's values in the console.. but when I call this.sendInfoToB(true); from componentA's ngOnInit() then I get no message in console for componentB. I want the message when I call from componentA's ngOnInit. How can I achieve that? Please help. Thank you in advance.
ComponentA.ts
constructor(private siblingService: SiblingService,) {}
public dataX: boolean = false;
someFunc(){
//some calculation returning true
this.dataX = true;
}
ngOnInit() {
this.someFunc();
this.sendInfoToB();
}
sendInfoToB() {
this.siblingService.communicateMessage(dataX);
}
message.service.ts
export class SiblingService {
sendMessage = new Subject();
constructor() {}
communicateMessage(msg) {
this.sendMessage.next(msg);
}
}
ComponentB.ts
constructor(private sibService: SiblingService,) {}
ngOnInit() {
this.sibService.sendMessage.subscribe((message) => {
this.check = message;
console.log(this.check);
console.log(message);
});
}
More than likely this has to do with order of operations. Component A is created and sends the message, then Component B gets created and subscribes to new messages. Since you are using a Subject it only gives you messages sent after you subscribe to it.
The easiest strategy to this is to use a BehaviorSubject.
export class SiblingService {
sendMessage = new BehaviorSubject();
constructor() {}
communicateMessage(msg) {
this.sendMessage.next(msg);
}
}
The other way is to send the message after the init happens, like on a click event.