What is the retry mechanism for Http Requests in Angular 4?

As I delve into Angular4, my focus lies on creating a request/response intercept mechanism. Despite being new to observables, I am determined to implement this feature.

In order to achieve this, I have established two arrays for interceptors – one for requests and the other for responses. Interceptors essentially consist of functions that take in request/response objects and modify them as needed.

sendRequest(req:Response):Observable<Response>{
    req= this.processRequest(req);

    This.http.request(req)
           .map( (res:Response)=>{
                return this.processResponse(res)
            })
            .catch(this.handleError)
}

handleError(err:Response):Observable<Response>{
    return Observable.throw(err);
}

While the basic error handling is operational, there are instances when I encounter a 401 exception and require a new Auth token to retry the same request with the updated token.

My current approach involves introducing an array of error interceptors. One such function within these error interceptors would specifically address a 401 status code by initiating a refresh request to obtain a new token, thereby overriding any subsequent error interceptor functions. I anticipate needing to switch the observable stream accordingly, ultimately ensuring the observer receives the response from the most recent request made. How should I proceed with this?

Answer №1

Here is a suggestion:

Consider using the following code snippet: this.http.get('some/url').retry(2)......

Answer №2

It appears more convenient to handle it at the same level as http.request instead of having to manage all the information needed to reissue the request separately. However, if that poses no difficulty...

I assume your interceptors are modifying the request object directly and returning a modified copy of the request object. For instance, something like this...

transformResponse(response) {
  for(let interceptor of interceptors) {
    response = interceptor(response);
  }
  return response;
}

Where the interceptor has the following structure:

interface Interceptor<T> {
  (rsp: T): V;
}

Would it be possible to alter the interceptor structure to something like

interface Interceptor<T> {
  (rsp: T): T | Promise<T> | Observable<T>;
}

Then you could implement...

transformResponse(responseObs: Observable<any>) {
  for(let interceptor of interceptors) {
    responseObs = responseObs.flatMap(interceptor);
  }
  return responseObs;
}

This modification would enable an interceptor to perform an asynchronous transformation on the response (like reissuing the request).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it considered an anti-pattern for certain components within a tile system to share a viewmodel when the parent web component has multiple child components?

Creating an Angular application involves a parent component that contains child components. I am looking for a way to share functionality among the components without resorting to creating services for each one. One approach would be to build services and ...

Angular HTTP requests may not always have the same JSON key in their response

As I navigate through the process of requesting data from an API that returns JSON, I have encountered a challenge - the key is not always consistent. However, based on the input parameters provided, I can predict what it will be. Despite my limited experi ...

Implementing strong security measures for Angular and .Net Core APIs using Azure AD authentication and defining specific application roles

My system is a combination of Angular front end and .Net Core API back end. Both are set up as distinct Active Directory apps in the Azure Portal. As a result, both applications are protected by Azure AD. The API is exposed and interacted with by authenti ...

Exploring the benefits of useContext in Expo router

Currently, I am working with the latest Expo-Router version which incorporates file-based navigation. To establish a universal language context in my application, I have utilized React's context API along with the useReducer hook. However, I am encoun ...

Utilizing a class member's data type

I need to inform Typescript that a member of my class is derived from another class. For instance: Class Main{ getDataFromChild(data){ console.log(data) } } Class Child{ getDataFromChild: Main.getDataFromChild } Scenario Application In my s ...

What is the best way to show the character count for every input in an Angular application?

In my app component, I have two input fields. I want to display the character count and max character limit for each input field dynamically as users type or blur on the input field. To achieve this, I created a component that shows and hides the characte ...

Discovering the functionality of es6 object.assign and find methods within a typescript file

Currently, I am in the process of transitioning from Java Script to TypeScript for my project. However, I am facing limitations as I am unable to utilize object.assign() and find methods. ...

Syncing data between local storage and a remote server using Ionic5 provider

I've been considering implementing a data provider that could store a duplicate of the backend data locally for quick access. I believe this concept is referred to as mirroring or something similar. Nevertheless, it must be synchronized and updated r ...

String interpolation can be used to easily accept numbers with dot separators

Is it possible to create a function that can accept numbers with dot separators? Here are some examples: func('100.000.002.333') // should pass func('10') // should pass func('20') // should pass func('100') // shou ...

Issue: Transition of FCM to HTTP v1 API from Previous Legacy API

Recently, I have been working on migrating FCM from the legacy API to the HTTP V1 API. Here's a comparison of the "working code before" and after the necessary modifications: Before: const payload = { data: ...

Tips on implementing computed properties in Vue.js while using TypeScript

There is a significant amount of documentation on how to utilize Vue.js with JavaScript, but very little information on using TypeScript. The question arises: how do you create computed properties in a vue component when working with TypeScript? According ...

Use ngClass to dynamically change the color of a button when it is clicked. This functionality can be applied to buttons

In my application, there are 80 buttons displayed on the screen using the following code: <tr *ngFor="let plans of PlanList"> <td class="text-primary">{{plans.typename}} </td> <td class="text-center&quo ...

The navigation underline stays in place even after being clicked, and also appears below

Take a look at this js fiddle I've managed to create the underline effect on the navigation links when the user hovers over them. However, the underline only stays visible until the user clicks elsewhere on the screen. How can I make it persist as l ...

The input of 'Response' does not match the expected type of 'string'

I am currently working on a project that involves retrieving books from the Google Book API using Angular 4. Although I am still learning Angular, I am facing challenges in understanding how to read the JSON response. During my research online, I came acr ...

How to minimize scaffolding with Redux, React, and Typescript?

Is there a way to avoid the process of instrumenting my Redux-Aware components? The level of scaffolding required seems excessive. Take, for instance, the minimal code necessary to define a redux-aware component: class _MyActualComponent extends React.Co ...

Deciphering the SessionProvider error: When "useSession" isn't recognized as a function

I recently started diving into React and NextJS, but I've been able to piece things together with the knowledge I have. Recently, I added social login functionality using Lucia auth and now I'm looking to implement a session provider to allow ac ...

Hide side navigation bar when clicking on the background

Exploring the world of Angular Material, ngrx, and modern Angular for the first time. Working on setting up a simple header layout with a toolbar containing a title and a menu icon, along with a sidenav to display links. The goal is to have the sidenav ope ...

Issue with maintaining session persistence in Angular 7 and Express

I am currently facing an issue with my Angular 7 app connecting to an Express API backend where the session doesn't seem to persist. Within Express, I have set up the following endpoint: router.get('/getsession', function(req, res) { c ...

Is TypeScript capable of comprehending Svelte components?

When it comes to Svelte, the final output is native JavaScript classes, which TypeScript can understand. However, before TypeScript can recognize Svelte components, they must first be compiled from their initial .html form. This can lead to a 'cannot ...

Creating a downloadable text file in Angular

I need help with including data retrieved from an API GET call into a text file within my project. I have successfully called the API, displayed the data on the console and the webpage, but now I am struggling to save this data into a text file. Below is t ...