hugonne
hugonne

Reputation: 431

Angular 9: Notify "unrelated" component of action taken

I have a top-nav component that I use in my app.component. In that top nav, there's a button that changes a global filter. I need to be able to notify the component currently loaded in my router-outlet that the filter was changed, so if refreshes its data based on the new filter.

This is a simplified snippet of how my app-component looks like:

<app-top-nav></app-top-nav>
<router-outlet></router-outlet>

So, something happens in my top-nav, and I emit an event from there. Now, I need to be able to notify the current component of that change (the component currently loaded via the router outlet). How do I achieve that? They are not really siblings or have a parent-child components, so I'm stuck.

Thanks a lot.

Upvotes: 0

Views: 929

Answers (2)

hugonne
hugonne

Reputation: 431

O managed to solved it by using a service, which acts as an intermediary. top-nav changes the filter via that service, and that service emits the event, instead of top-nav. The other component subscribes to the event emitted by the service.

Service:

export class MasterFilterService {
    @Output()
    filterChange = new EventEmitter<void>();
    getFilterChangeEmitter() {
        return this.filterChange;
    }
    changeFilter() {
       ...
       this.filterChange.emit()
   }
}

Routed component:

subscription: any;
constructor(
    private readonly masterFilterService: MasterFilterService) {
    this.subscription = this.masterFilterService.getFilterChangeEmitter()
        .subscribe(() => {
            //Do whatever needs to be done in response to the event
            this.resetGrid();
        });
}

Upvotes: 1

Cagri Tacyildiz
Cagri Tacyildiz

Reputation: 17610

u can share data with service between unrelated components.

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class ShareService  {   
  constructor() { } 
  private paramSource = new BehaviorSubject("");
  sharedData = this.paramSource.asObservable();
  setParam(param:string) { this.paramSource.next(param)}    
}

put in providers in appmodule

providers:[ShareService ]

put in constructors in components

constructor(private shareService: ShareService  ){}

from first component send like

this.shareService.setParam('Sending param');

from second component receive like

 this.shareService.sharedData.subscribe(data=> { console.log(data); })

Upvotes: 1

Related Questions