2016-11-24 60 views
0

在這個角2應用程序中,可以同時觸發多個HTTP請求。這些是從同一個組件的實例觸發的,但是這些組件中的許多可以一次顯示在頁面上。角2可觀察多個http請求單令牌

服務器在發出數據之前需要檢索令牌。現在每當例如6個請求被同時觸發時,爲每個請求執行檢查以查看令牌是否有效。如果它是無效的,但它們不會等待第一個請求的響應並將該標記用於其他請求。

我正在使用mergeMap來確保在檢索到令牌後執行數據請求,這使得應用程序可以正常工作。不過,我希望它不會在同時觸發請求時檢索多個標記。

我一直在嘗試很多事情,但我似乎無法找到適用於我的方案的解決方案。我會感謝您可能會給予的任何幫助。 查看我在下面嘗試的一些代碼。

獲取

Get = (path: string): any => { 
    if (this.authentication.isAuthenticated()) { 
     this.SetAuthorizationHeader(this.authentication.token); 
     return this.GetRequest(path); 
    } else { 
     return this.authentication.getToken() 
      .mergeMap(prop => { 
       this.authentication.setToken(prop); 
       this.SetAuthorizationHeader(this.authentication.token); 
       return this.GetRequest(path); 
      }); 
    } 
} 

爲gettoken

getToken(): Observable<Response> { 
    if (!this.requestInProgress) { 
     this.requestInProgress = true; 
     let urlSearchParams = new URLSearchParams(); 
     urlSearchParams.append('client_id', Constants.CLIENT_ID); 
     urlSearchParams.append('grant_type', Constants.GRANT_TYPE); 
     let body = urlSearchParams.toString() 
     this.pendingRequest = this.http.post(`${this.configuration.BaseUrl}`, body, { headers: this.configuration.Headers }) 
      .map(this.extractData) 
    } 
    return this.pendingRequest; 
} 
+0

http://stackoverflow.com/questions/36271899/what-is-the-correct-way-to-share-the-result-of-an-angular-2-http-network-call-in是關於如何防止對同一數據的多個請求。 –

回答

0

通過使用建議的修正:https://stackoverflow.com/a/36296015/5219786

爲gettoken

getToken(): Observable<Response> { 
    if (!this.requestInProgress) { 
     this.requestInProgress = true; 
     let urlSearchParams = new URLSearchParams(); 
     urlSearchParams.append('client_id', Constants.CLIENT_ID); 
     urlSearchParams.append('grant_type', Constants.GRANT_TYPE); 
     let body = urlSearchParams.toString() 
     this.pendingRequest = 
     this.http.post(`${this.configuration.BaseUrl}`, body, { headers: this.configuration.Headers }) 
       .map(this.extractData) 
       .publishLast() 
       .refCount(); 
    } 
    return this.pendingRequest; 
}