Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

275
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda