Search code examples
angularrxjsobservableswitchmap

angular async reloading spinner


I have a simple setup to show a loading spinner when the async pipe is null:

<div *ngIf="(searchResults$ | async) as searchResults; else loading">
</div>
<ng-template #loading>
    loading..
</ng-template>

However, when the user searches again for a second time, the loading.. doesn't show, I suppose I need this searchResults$ observable to emit null to show the spinner again, or have a separate isLoading variable.

what's the best way of doing that?

if it matters, i've got a debounce and a switchMap (i.e. tricky using finalize etc)

this.searchResults$ = this.filters$
      .pipe(
        debounceTime(200),
        distinctUntilChanged(),
        switchMap((f) => {
            return httpGet(f)
        })
      )

also, I tried *ngIf="!isLoading && (searchResults$ | async) as searchResults but found it problematic, e.g. searchResults$ not subscribed to, or angular complaining about changes after change detection


Solution

  • I now use the ngx-http-request-state library which gives loading, error and render states. It also can work on reloads if you use scan() or withLatestFrom(). Also it works from inner observables.

    If using graphql, I consider using a combination of options of fetchPolicy, loading, and networkStatus.