1

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
}
2
  • You should use HttpInterceptor. Commented Dec 6, 2017 at 18:06
  • .catch<any, LegalTerm>(this._trace.handleError) is code that will bite you sooner or later. Fix it. Commented Dec 6, 2017 at 21:26

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

import 'rxjs/add/operator/finally'; is what I needed, thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.