Search code examples
angularrxjsobservableangular-httpclient

Angular HttpClient error handling


I am struggling a bit with how to execute code after an error happened in HttpClient. I would like to know how to set the flag that would turn off a loading spinner when the http called failed. I am using RxJs 5.5.2 and Angular 5

  private fetch(): Observable<LegalTerm[]> {

    this.isLoading = true;
    return this._http
                .get<LegalTerm[]>(AppSettings.LegalTermUrl, { withCredentials: true })
                .do(() => this.isLoading = false)
                .catch<any, LegalTerm>(this._trace.handleError)
                .do(() => this.isLoading = false)
  }

So in the happy path isLoading = false works but not sure how to do that after catch. It is not working the way the code is now. I am also using a custom error handler as per Angular docs

public handleError<T>(operation = 'operation', error: any, result?: T) {
   // do logging etc
   return Observable.of(result as T); // return empty result
}

Solution

  • You could use the finally operator to change the flag to false on complete/error events.

    This could be done as follows:

    import { BehaviorSubject }from 'rxjs/BehaviorSubject';
    import 'rxjs/add/operator/finally';
    
    @Component()
    export class FooComponent {
      private loadingSub$ = new BehaviorSubeject<boolean>(false);
      loading$ = this.loadingSub$.asObservable();
    
      constructor(private fooService: FooService){
      }
    
      fetch(){
         this.loadingSub$.next(true);
         this.fooService.getData() 
         // notice that getData() returns a stream that isnt infinite
         .finally(()=>this.loadingSub$.next(false))
         .subscribe(fooData => console.log(fooData)); // error handling not considered
       }  
    }
    
    @Injectable()
    export class FooService {
       constructor(private http: HttpClient){}
    
       getData(): Observable<any>{
          // error handling not considered
          return this.http.get('foourl');
       }
    }
    

    More info about the operator can be found here