How to show a loading spinner while waiting on an observable getting data from a service in Angular

前端 未结 6 1427
情书的邮戳
情书的邮戳 2020-11-27 08:35

I have set up an observable service that helps me persist data, but I need a way to show a loading spinner while the data is waiting to come from the observable.

My

6条回答
  •  鱼传尺愫
    2020-11-27 08:58

    You can create a loading pipe for that, the benefit is that you can use it everywhere in your app

    import { Pipe, PipeTransform } from '@angular/core';
    import { isObservable, of } from 'rxjs';
    import { map, startWith, catchError } from 'rxjs/operators';
    
    @Pipe({
      name: 'withLoading',
    })
    export class WithLoadingPipe implements PipeTransform {
     transform(val) {
       return isObservable(val)
          ? val.pipe(
             map((value: any) => ({ loading: false, value })),
             startWith({ loading: true }),
             catchError(error => of({ loading: false, error }))
          )
         : val;
     }
    }
    

    here is you http call

    httpCallObservable$ = this.httpClient.get(url);
    

    and use it like this in your template

     
    Value: {{ data.value }}
    Error {{ data.error }} Loading...

提交回复
热议问题