How can I implement timeout for angular2+ http request

前端 未结 4 1643
迷失自我
迷失自我 2020-12-01 18:22

Here is just regular request looking like that:

this.people = http.get(\'http://localhost:3000/users\')
                  .map(response => response.json()         


        
4条回答
  •  旧时难觅i
    2020-12-01 18:41

    As with the new version, you must pipe to use the timeout. And to get the response you can use map inside. The complete code is as below.

    import { map, timeout, catchError } from 'rxjs/operators';

    const sub: any = this.httpClient.post(this.baseUrl, body)
        .pipe(timeout(Config.SesamTimeout),
            catchError((err: any) => {
                this.handleTimeout(err);
                return of(null);
            }),
            map((v: SesamResponse) => {
                if (v) {
                    const a: SearchResultGroup[] = this.convertSesamResponseToApiFileItem(v);
                    return a;
                }
            }));
    

    Here Config.SesamTimeout is the time in milliseconds.

提交回复
热议问题