Currently, I am incorporating an observable concept into my application. In this setup, a service is called by component1 to emit an event that is then subscribed to by component 2.
Below is the code snippet for reference:
Service Code
export class MessageService {
private subject = new BehaviorSubject<any>("");
message$ = this.subject.asObservable();
sendMessage(message: string) {
console.log('sendMessage', message)
this.subject.next({ text: message });
}
clearMessage() {
this.subject.next("");
}
Component1 Code
this.data.sendMessage('Printed');
Component2 Code
providers: [JsonDataService, MessageService]
constructor(public data?: MessageService) {}
ngOnInit() {
this.data.message$.subscribe(res => { console.log('response', res); }, err => { console.log('error', err) });
}
While the sendMessage function successfully logs messages passed to it in the console, I am facing issues with receiving any responses or output from the subscription method defined in component2.