【问题标题】:Set variable at start and end of http call in more than one location在多个位置的 http 调用开始和结束时设置变量
【发布时间】:2016-12-17 02:03:20
【问题描述】:

我有一个 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() 函数时,load() 和 reload() 的开始和结束变量必须同时为同一个 http 调用设置。我怎样才能做到这一点?

【问题讨论】:

    标签: http angular rxjs angular2-observables


    【解决方案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();
    

    【讨论】:

    • 这行不通。我会用我找到的解决方案发布答案​​。
    【解决方案2】:

    我是这样解决的:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多