Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

270
Views
When pass a selected item through a shared service between to component, how to respond all changes, not just onInit?

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
    }
  }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!