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

77 views Asked by At

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?

2

There are 2 answers

0
AudioBubble On BEST ANSWER

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
1
rgk On

Try this.

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