簡體   English   中英

如何訂閱正在進行的http請求

[英]How to subscribe to an ongoing http request

我只需要從服務器請求一些數據,然后只要加載了應用程序就可以使用它

getData(callback: Function) {
 if (this.data) {
  callback(this.data);
 } else {
  this.query.http.get('url', res => {
   this.data = res;
   callback(this.data);
  });
 }
}

問題是,當應用程序啟動時,許多組件立即請求數據,導致30-40 http請求,因此我想出了以下解決方案:

getData(callback: Function) {
 if (this.data) {
  callback(this.data);
 } else if(!this.gettingData) {
  this.gettingData = true;
  this.query.http.get('url', res => {
   this.data = res;
   callback(this.data);
  });
 } else {
  setTimeout(() => {
   getData(callback);
  }, 500)
 }
}

因此,如果http請求正在進行,它將在500毫秒后再次請求數據,如果請求返回錯誤,我將Gettingdata重置為false,它可以正常工作,但是感覺很臟和有錯誤,我該如何訂閱由調用的正在進行的http請求另一個函數調用器?

這個怎么樣?

getData () {
    this.query.http.get('url'). subscribe(
    res=> this.data = res,
    err=> console.log(err));
}

然后只要在整個組件中使用this.data,就可以從子組件中發出數據,就像這樣

@Output() valueChange = new EventEmitter();

private data;

getData () {
    this.query.http.get('url'). subscribe(
    res=> {
          this.data = res;
          this.valueChange.emit(this.data);
    },
    err=> console.log(err));
}

我希望這有幫助。 或有點回答你的問題

引入一項管理您的http請求的服務。 服務基本上是一個單例,可以通過依賴注入來使用。 用它創建

ng -generate service myservice

並通過聲明類型為myservice的字段作為組件的構造函數參數來注入它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM