xxxxxxxxxx
this.CommonService.updateListsObs
.subscribe(
(response) => {console.log("You will get date range in response which can be used to filter Car list in Component A ")}
)
xxxxxxxxxx
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class CommonService {
private subjectName = new Subject<any>(); //need to create a subject
sendUpdate(message: string) { //the component that wants to update something, calls this fn
this.subjectName.next({ text: message }); //next() will feed the value in Subject
}
getUpdate(): Observable<any> { //the receiver component calls this function
return this.subjectName.asObservable(); //it returns as an observable to which the receiver funtion will subscribe
}
}
xxxxxxxxxx
import { Component } from '@angular/core';
import { CommonService } from 'provide proper path';
@Component({ templateUrl: 'sender.component.html' })
export class SenderComponent {
constructor(private Service: CommonService) { } //mention the service in constructor
sendMessage(): void {
// send message to subscribers via observable subject
this.Service.sendUpdate('Message from Sender Component to Receiver Component!');
}
}
xxxxxxxxxx
import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { CommonService } from 'provide proper path';
@Component({
templateUrl: 'receiver.component.html'
})
export class ReceiverComponent implements OnDestroy {
messageReceived: any;
private subscriptionName: Subscription; //important to create a subscription
constructor(private Service: CommonService) {
// subscribe to sender component messages
this.subscriptionName= this.Service.getUpdate().subscribe
(message => { //message contains the data sent from service
this.messageReceived = message;
});
}
ngOnDestroy() { // It's a good practice to unsubscribe to ensure no memory leaks
this.subscriptionName.unsubscribe();
}
}