Search code examples
httpangularrxjsangular2-observables

Set variable at start and end of http call in more than one location


I have an AngularJS 2 application and I want to run an http call and set some variables when it starts and ends. The problem is that I need to do this in different locations for the same call.

constructor(
  private http: Http
) {}

fetch() {
  return this.http
    .get('assets/data/events.json')
    .map(response => response.json());
}

load() {
  let isLoading = true; // set variable at start
  return this.fetch() // call fetch()
    .finally(() => isLoading = false); // set variable at end
}

reload() {
  let isReloading = true; // set variable at start
  return this.load() // call load()
    .finally(() => isReloading = false); // set variable at end
}

this.reload(); // start call

When I call the reload() function the start and end variables of the load() and reload() must be set at the same time for the same http call. How can I achieve this?


Solution

  • I solved it this way:

    constructor(
      private http: Http
    ) {}
    
    fetch() {
      return this.http
        .get('assets/data/events.json')
        .map(response => response.json());
    }
    
    load() {
      let share = this
        .fetch()
        .share();
      let isLoading = true; // set variable at start
      share
        .finally(() => isLoading = false)  // set variable at end
        .subscribe();
      return share;
    }
    
    reload() {
      let isReloading = true; // set variable at start
      return this.load() // call load()
        .finally(() => isReloading = false) // set variable at end
        .subscribe();
    }
    
    this.reload(); // start call