Jean Catarina
Jean Catarina

Reputation: 51

Angular 4 - timeout request

I want to make requests every 1 second but my timeout does not work.

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

Upvotes: 1

Views: 2778

Answers (2)

Michael Kang
Michael Kang

Reputation: 52867

Timeout is for raising a timeout error if an event isn't emitted within a certain time period. You probably want Observable.interval:

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

if you want to serialize the requests so that it runs 1 second after the other, use concatMap instead.

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

Upvotes: 1

Aravind
Aravind

Reputation: 41581

Use debounceTime operator as below

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[]);

Upvotes: 0

Related Questions