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

264
Visualizações
Changing observable value in a component doesn't trigger subscribe in a service

I have a scenario where I send data from a component to a service which then manipulates data. The idea was that when I fetch data in the component that I push the change to a BehaviorSubject variable using next.

For some unbeknown to me reason, this.person.subscribe() doesn't get triggered when passing the value using next. However, when I check if the value in the service was changed I see that it was properly updated.

Component

  constructor(private incomeService: IncomeService) {
  }

  ngOnInit(): void {
    // Fetching data from a service 

    this.person = fetchedTestData;

    // This doesn't trigger subscribe method in the service
    this.incomeService.person.next(fetchedTestData);

    // The data is definitely changed because the value is correctly set
    console.log(this.incomeService.person)
  }

Service

person: BehaviorSubject<any> = new BehaviorSubject<any>(null);
  
constructor() {
    this.person.subscribe(person => {
      // Do something else
    });
  }

What seems to be the culprit here?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Generally Angular services are meant to handle data retrieval and all business logic, while the components subscribe to Observables for display purposes.

If I understand your situation correctly, you'd be better off doing something like this:

Service

public person$$ = new BehaviorSubject<unknown>(null);
public person$ = this.person$$.asObservable();

public getPerson(): void {
    // logic for retrieving data
    this.person$$.next(response);
}

Component

public person$ = this.incomeService.person$;

// if you wanted to use console for debugging you could also add
// .pipe(tap(person => console.log(person)))
// which would log to console whenever the person$$ subject is updated in the service

constructor(private incomeService: IncomeService) {}

ngOnInit(): void {
    this.incomeService.getPerson();
}

Template

<ng-container *ngIf="person$ | async as person">
{{ person | json }}
</ng-container>

In this case, because the async pipe is used in the template, it automatically handles the subscription (and unsubscribing when the component is destroyed). You could also .subscribe in the component logic, just make sure to have an unsubscribe call in there somewhere to prevent memory leaks.

over 4 years ago · Santiago Trujillo Relatório

0

In the service you have person as a behavior subject. You'd update it there not in your component.

component

this.incomeService.updatePerson('something');

service

constructor() {
    this.person.subscribe(person => {
        console.log(person);
    });
}

updatePerson(arg:string){
    console.log('is this happening?', arg);
    this.person.next(arg);
}
over 4 years ago · Santiago Trujillo Relatório

0

The problem was in a function that was generating an error and that is executed before calling next. Unfortunately I missed it because errors in my Google Chrome console were hidden.

So as a reminder for anyone else having a similar problem; check that your methods are running error free before panicking.

over 4 years ago · Santiago Trujillo 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