Posted onEdited onInrxjs Symbols count in article: 432Reading time ≈2 mins.
Introduction
In RxJS, there is a timeout operator, it’s used to throw an error if the source observable does not emit a value within a specified timeout duration.
Use case
In Angular, the HttpClient service is used to make HTTP requests. Sometimes, we want to set a timeout for the request, if the request does not complete within the specified time, we want to cancel the request and show an error message to the user.
getData() { returnthis.http.get('https://example.com/api/data').pipe( timeout(10000), // 10 seconds catchError((error) => { // Handle timeout or other errors console.error('Request timed out or failed', error); returnthrowError(error); }) ); } }
But, wait, what if I want to add this timeout for all my requests? Do I need to add the timeout operator to every request? The answer is no, you can create an interceptor to add the timeout operator to all requests.
Now, all your HTTP requests will have a timeout of 10 seconds.
But, what if I want to set different timeout values for some specific requests? You can add a custom header to the request and check it in the interceptor, if custom header timeout exists, use the custom timeout value, otherwise use the default timeout value.