0

Mg goal is when I select an item from dropdown, which is in a button component, then it passes the item to a table component throughout a shared service. I need this to change the table by just showing the selected element. Now, if I select the element, it changes the service data to the selected item, but the table component checks the service data onInit (when nothing is selected yet), and if I select an item, it doesen't checks again. Just once on init. What should I do to make the table component constantly watch if the service data changed? I thought about observable, but I don't know how to implement it in my code.

My service:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class SharedDataService {
  selectedData: object = {};

  constructor() {}

  setSelectedData(data: object) {
    this.selectedData = data;
  }

  getSelectedData() {
    return this.selectedData;
  }

Button Component:

  onSelect(company: any) {
    for (var i: number = 0; i < this.items.length; i++) {
      if (this.items[i].id == company.target.value) {
        this.selectedCompany = this.items[i];
        this.sharedData.setSelectedData(this.selectedCompany); //pass data to service
      }
    }
  }

Table Component:

  ngOnInit(): void {
    this.onGetItems();
    this.selectedCompany = this.sharedData.getSelectedData();
    if (Object.getOwnPropertyNames(this.selectedCompany).length === 0) { //if nothing was selected
      //do nothing
    } else {
      //refresh the table with displaying that one item only
    }
  }

1 Answers1

0

Instead of just get and set a variable in a service switch to using rxjs behavior subject. So with this you can just subscribe to the variable in the service where you can listen to all the changes.

You can find a similar example here - https://stackoverflow.com/a/57355485/7203750

krishna217
  • 13
  • 5