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

318
Visualizações
Angular: Keep the previous value of the observable

I am sending an HTTP request to a backend and receiving the data. I am passing the data through an observable stream and directly subscribing it in my HTML template using async pipe. However, I am having an issue. Since, I want to send multiple requests on the click of the button again and again, I want the observable to keep adding the new values to the data stream instead of entirely replacing the previous ones. How can I do that?

Here's my code:

TS

productsData$ = this.productService.getProduct(this.payload);

loadMore()
{
   ....
   this.productsData$ = this.productService.getProduct(updatedpayload);
}

HTML

<div class = "grid" *ngIf="productsData$ | async as productsData">
    <div class="p-col-12 p-md-6 p-lg-3" *ngFor = "let pData of productsData; let i = index">
...

How can I retain the previous values in the observable stream while sending an HTTP request and adding the new ones to the existing?

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

0

I agree with the comments. You can create a cache array and leverage that to return the previous values as well.

private readonly previousProductsData = [];

readonly buttonTrigger$ = new BehaviourSubject('');

productsData$ = this.buttonTrigger$.pipe(
  switchMap(()=> this.productService.getProduct(this.payload)),
  tap((product)=> {
    this.previousProductsData.push(product)
  }),
  map(()=> this.previousProductsData)
);

and the button click could look like:

loadMore()
{
   ....
  this.productService.buttonTrigger$.next('');
}
over 4 years ago · Santiago Trujillo Relatório

0

Try merge from rxjs

productsData$ = this.productService.getProduct(this.payload);

loadMore(){
  ....
  this.productsData$ = merge(this.productsData$, this.productService.getProduct(updatedpayload));
}
over 4 years ago · Santiago Trujillo Relatório

0

push the response to an array and use that to display

this.productsData$ = this.productService.getProduct(updatedpayload);
this.productArray.push(this.productsData$);

And display productArray

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