Home > OS >  Send "Error time out" after specific amount of time in angular
Send "Error time out" after specific amount of time in angular

Time:01-15

I am making a API call but sometimes it is taking more time to get the response. I want to set a specific amount of time, lets say "8secs", to wait for the response if the time mention before has pass the API call should stop and show in console "ERROR time out".

I have tried adding the timeout in a pipe as other posts says like this:

`this.http.post<RefreshTokenResponseMessage>(url, tokenRequestMessage, { headers }).pipe(timeout(20)).toPromise()`

but it is showing an error with the timeout there.

I also try adding the timeout param in the header like this:

`const headers = new HttpHeaders({authorization: 'Bearer ${sessionstorage.getItem('authData')}',timeout: '${2}',});
return this.httpClient.get(URL, { headers });`

But I am also facing the same issue that it is not triggering the error.

Has anyone encounter something like this?

CodePudding user response:

If you want to output a console.error if the http response has not arrived after 8 seconds, you can do this as follows:

this.http.post<RefreshTokenResponseMessage>(url, tokenRequestMessage, { headers }).pipe(
    tap((res) => console.log('Result:', res)),
    timeout(8000),
    catchError(_ => {
        console.error('ERROR time out');
        return EMPTY;
    })
)       
.subscribe();
  • Related