在多个位置的 http 调用的开始和结束处设置变量

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

我有一个 AngularJS 2 应用程序,我想 运行 一个 http 调用并在它开始和结束时设置一些变量。问题是我需要在不同的位置为同一个电话执行此操作。

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

当我调用 reload() 函数时,对于同一个 http 调用,load() 和 reload() 的开始和结束变量必须同时设置。我怎样才能做到这一点?

试试这个。

    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();

我是这样解决的:

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