2017-06-17 53 views
0

我想每隔1秒發一次請求,但超時不起作用。Angular 4 - 超時請求

matchlist.service.ts

import 'rxjs/add/operator/toPromise'; 
import 'rxjs/add/operator/timeout'; 

getMatch(matchId: number): Promise<Match[]> { 
    let matchUrl: string = 'https://br1.api.riotgames.com/lol/match/v3/matches/'+ matchId +'?api_key='; 

    return this.http.get(matchUrl)  
     .timeout(1000)     
     .toPromise() 
     .then(response => response.json().participants as Match[]); 

}; 

matchlist.component.ts

self.matchlist.forEach(function(matches){     
      self.MatchlistService.getMatch(matches.matchId) 
       .then((match: Match[]) => { 
        self.match = match; 
        return self.match; 
       }).catch(
        err => console.log(err) 
       );       
     }); 
+0

你有什麼錯誤嗎? – Aravind

+0

沒有錯誤,只有forEach一次執行所有請求 –

回答

0

使用debounceTime操作如下

getMatch(matchId: number): Promise<Match[]> { 
    let matchUrl: string = 'https://br1.api.riotgames.com/lol/match/v3/matches/'+ matchId +'?api_key='; 

    return this.http.get(matchUrl)  
     .debounceTime(1000)     
     .toPromise() 
     .then(response => response.json().participants as Match[]); 
+0

不工作:(在1秒內15請求,「狀態碼:429太多請求」 –

+0

因爲有很多服務調用是在短時間內做出的,所以你的服務器是拒絕他們 – Aravind

1

超時是判定事件養超時錯誤在特定時間段內不發射。你可能想Observable.interval:

return 
    Observable.interval(1000).mergeMap(t=> this.http.get(matchUrl)) 
    .toPromise() 
    .then(response => response.json().participants as Match[]); 
如果你想要序列化的要求,使其運行其他1秒後

,使用concatMap代替。

return 
    Observable.interval(1000).concatMap(t=> this.http.get(matchUrl)) 
    .toPromise() 
    .then(response => response.json().participants as Match[]); 
+0

不要工作:(15秒中的請求,「狀態碼:429太多請求」 –

+0

它停止1秒,然後立即執行所有請求 –

+0

啊,如果你想序列化請求,以便它運行1秒後,使用concatMap來代替 – pixelbits