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

137
Visualizações
RXJS ANGULAR - Observable still called after takeWhile operator is resolved

I am storing data in the session storage with an expiry date :

private saveSessionData<T>(key: string, value: T) {
    const item = {
      value: value,
      expiry: Date.now() + 10 * 60000 // 10 minutes from now
    }
    sessionStorage.setItem(key, JSON.stringify(item));
  }

I have an other function to access those data, that will return null if the data I try to access is expired :

private async getSessionData<T>(key: string): Promise<T | null> {
    const itemStr = sessionStorage.getItem(key);
    const item = JSON.parse(itemStr);
    if (Date.now() > item.expiry) {
      console.log('CONSOLE NULL');
      await this.alertService('OBJ EXPIRED');
      return null;
    }
    return item.value;
  }

I access those data like that :

getMyObj$ (): Observable<MyObj| null> {
    return from(this.getSessionData<MyObj>(this._myObj))
      .pipe(
        takeWhile(myObj => myObj != null),
        tap(x => console.log('getting my Obj')
    );
  }

In my View, I'm using the | async to show myObj with a two way data binding :

<div *ngIf="!!(getMyObj$ | async) as obj">
  <div>{{ obj }}</div>
</div>

My thought would be that my console show me the getting my Obj again and again until the expiry date is overdue, and then to see the alert message : OBJ EXPIRED with the console message CONSOLE NULL once. But currently, after the getting my Obj message, I have infinite CONSOLE NULL messages (that makes my browser crash) and the alert event is never shown.

Any one got any idea ? I have no idea what could makes that crash like that.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This is probably because of angular change detection, causing it to repeatedly call that method and subscribe to a new observable each time. You should instead create the observable once and share it:

this.getMyObj$ = 
  interval(1000).pipe(
    concatMap(() => this.getSessionData<MyObj>(this._myObj)),
    takeWhile(myObj => myObj != null),
    tap(x => console.log('getting my Obj'),
    shareReplay(1)
  );
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