Develop a brand new feature for subscribing to events from the ProductFilterComponent
.
import { Injectable } from '@angular/core';
import { Observable, Subject, ReplaySubject } from 'rxjs';
@Injectable()
export class EventSubscribeService {
private eventSubject: Subject<any> = new ReplaySubject(1);
constructor() { }
// set observable of this subject
get $getEventSubject(): Observable<any> {
return this.eventSubject.asObservable();
}
// remove from observer
resetEventObserver(): void {
this.eventSubject = new ReplaySubject(1);
}
// send event to observers
sendCustomEvent():void {
this.eventSubject.next(true);
}
}
Then include this service as a provider
in the Module that contains the ProductCompont
and its child components.
@NgModule({
...
providers: [
...
EventSubscribeService
...
],
...
The next steps are quite simple. (* Just a reminder to define an instance of the service in the constructor. I mention this because you're still getting familiar with Angular. Hopefully, you already know how to use services. Sorry for the repetition :)).
The FilterChangeEvent
in the ProductFilterComponent
could be implemented like this.
EDIT : Template of ProductFilterComponent
...
<button class="btn btn-default" (click)="onFilterChangeEvent($event)">ChangeFilterButton<button>
...
UPDATE : Handling the Button Click Event
onFilterChangeEvent(param:any):void {
this.serviceInstance.sendCustomEvent();
}
Lastly, subscribe to the event in the ProductListComponent
.
constructor(
private serviceInstance: EventSubscribeService,
) {
this.serviceInstance.$getEventSubject.subscribe(event => {
// Perform desired actions here
});
}
ngOnDestroy() {
this.serviceInstance.resetEventObserver();
}