Home > Back-end >  angular observable to only update it's parent subscriber with multiple components on the page
angular observable to only update it's parent subscriber with multiple components on the page

Time:04-22

I have 2 of the same components on the screen. Each component is a table where you can show/hide the columns.

<Customtable>
   <child 1>
     ...
      <child 5>
</component 1>

<Customtable>
   <child 1>
     ...
      <child 5>
</component 1>

I have some observables where child 5 passes data through a Observable which is subscribed from in it's parent. Child 5 emit subscription -> Customtable.

  Export Class ColumnDisplayService {
     visibleColumns = new BehavorSubject<Column[]>([]);

     visibleColumnObservable = this.visibleColumns.asObservable();


    updateVisibleColumns(columns: any[]){
      this.visibleColumns.next(colums);
    }
   }

and then the parent component Customtable subscribes as

...
this.columnDisplayService.visibleColumnObservable.subscribe(columns => {
  ...set new visible columsn 
});

Now this works for when 1 component is on the screen. But when I have 2 components, both are updated. so If I filter <Customtable> it filters every other <Customtable>. However I only want the child to update it's parent and not the other subscribers. Is this possible with out emitting an event up every child component with event.emit()

CodePudding user response:

I would suggest providing the ColumnDisplayService in your parent component (not in the module nor the root), which will allow you to isolate the instances of visibleColumnObservable from each other, and each one of them will be used in this component and its component tree.

@Component({
  //...
  providers: [ColumnDisplayService],
})
export class Customtable {
  constructor(private columnDisplayService: ColumnDisplayService) {
    //...
    // This service will be used in this component and its component tree:
    this.columnDisplayService.visibleColumnObservable.subscribe(columns => {
      ...set new visible columsn 
    });
  }
}
  • Related