1

我有一个 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() 的开始和结束变量。我怎样才能做到这一点?

4

2 回答 2

1

尝试这个。

    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();
于 2016-12-17T06:07:25.843 回答
0

我是这样解决的:

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
于 2016-12-17T18:52:23.423 回答