Angular 4 - 超时请求

时间:2017-06-17 22:52:57

标签: angular

我想每1秒发出一次请求,但我的超时时间不起作用。

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)
                );                        
        });

2 个答案:

答案 0 :(得分: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[]);

答案 1 :(得分: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[]);