angularasync-awaitpromiserxjsngrx

lastValueFrom unreliable when refresh page


I have an Angular/Django app where, when I repeatedly refresh a page, in about 10% of cases, the result of lastValueFrom is empty. However, the rest of the time, I can see the correct data.

Here’s my code:

async ngOnInit() {
    this.goals$ = this.store.select(state => state.shortGoals.shortGoals);
    this.goals = await lastValueFrom(this.goals$.pipe(take(1)));

I have tried using delay, retry, and timeout, as well as a resolver, but the issue persists.


Solution

  • Could you try filter operator to allow only emissions that will have a value.

    this.goals = await lastValueFrom(this.goals$.pipe(
      filter((data: any) => !!data),
      take(1),
    );
    

    If that does not work, you can also try subscribing to the observable and getting the data.

    this.goals$.pipe(
      takeUntilDestroyed(),
      filter((data: any) => !!data),
      take(1),
    ).subscribe((data: any) => {
      this.goals = data;
    });