Creating a method in Angular that combines async/await functionality with Observables

After transitioning from using async/await to Observables in Angular, I am trying to refactor the following code snippet to make it work with Observables:

async refreshToken() {
    const headers = this.authStorage.getRequestHeader();
    const body = {
      refreshToken: this.authStorage.getStoredValue('refreshToken'),
    };
    const newAccessToken = await this.http
      .post<any>(ApiURLStore.REFRESH_TOKEN_URL, body, { headers: headers })
      .toPromise();

    this.authStorage.setValueToStore('accessToken', newAccessToken);
  }

Essentially, I want to convert this function into one that returns an Observable after making a POST request to the backend and updating authStorage:

refreshToken(): Observable<any> {
    const headers = this.authStorage.getRequestHeader();
    const body = {
      refreshToken: this.authStorage.getStoredValue('refreshToken'),
    };
    return this.http
      .post<any>(ApiURLStore.REFRESH_TOKEN_URL, body, { headers: headers });

    this.authStorage.setValueToStore('accessToken', newAccessToken);
  }

While this code technically works, I'm facing issues accessing authStorage within an Observable. I've tried using pipe and subscribe without success. Any suggestions on how to approach this problem?

Answer №1

To handle side effects, utilize the tap operator:

Implement your desired logic within the tap operator like this:
return this.http
    .post<any>(ApiURLStore.REFRESH_TOKEN_URL, body, { headers: headers })
    .pipe(
        tap(newAccessToken => this.authStorage.setValueToStore('accessToken', newAccessToken))
    );

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

The function getattribute() on the edge is malfunctioning and returning a null value

Has anyone encountered issues with the getAttribute() function while creating an extension for Edge? I am currently facing a problem where it is not returning the attributes of the element that I am searching for. This is what my code looks like on Edge a ...

The Next.js build encountered an error - unable to locate function in next/script module

While constructing a CMS using next.js, one of the key components is media management through Cloudinary. The integration of the Cloudinary Media Library widget was successful during development using next/script. However, an error has now emerged that pre ...

What is the best way to combine 4 small triangle pieces in order to create one large triangle?

Is there a way to create an image background with triangle shapes by combining small triangles together? I am interested in making this collection of triangle image backgrounds. Can someone guide me on how to do it?! .block { width: 0; height: ...

C# - Issue with Webbrowser failing to fully load pages

I am facing an issue with loading pages completely on the web browser, likely due to heavy usage of JavaScript. To address this problem, I have integrated another browser into the project called Awesomium. I am wondering if Awesomium supports using getEle ...

Dealing with incorrect routes found in both documents

In my current project, I am facing an issue where I need to handle invalid routes and display a message in Node.js. I have two separate files, one for users and one for tasks. If a user accesses a route that does not exist, I want to show an error message ...

Identify the row containing a value of null using jQuery (functionality not performing as anticipated)

Whenever the user clicks on the GetData button, I retrieve JSON data and display it in an HTML table similar to the demo below. Demo: https://plnkr.co/edit/I4XYY6CZohf7IS6wP8dR?p=preview There are instances where the value can be null, such as the loanNu ...

Utilizing mapped data to display numerous Material-UI Dialog elements

On my table, I have a list of users displayed. Each user has a button in their row to delete them. Clicking the delete button triggers a Material-UI Dialog to confirm. An issue arises where 3 dialogs are being rendered due to mapping, and the last dialog ...

How can I update the color scheme in styled components based on the active state of the component?

I'm currently working on a react accordion component that requires changing styles based on the active and inactive states. I have successfully set the state and added two props for color and active color. The goal is to change colors when the user cl ...

The absence of data in a c# web api controller is causing issues with jQuery AJAX post requests

When I am sending data to a c# web api controller, I use the following method: $.ajax({ type: "POST", url: "menuApi/menu/Cost", data: JSON.stringify(order), contentType: "application/json", success: function (data) { window.alert(&apo ...

React ensures that the page is not rerendered until after data has been fetched

I am dealing with the following code snippet. This is my React hook: const [isLoading, setIsLoading] = React.useState(true); useEffect(() => { setIsLoading(() => true); // I expect the page to rerender and display loading now. const select ...

An issue with Nuxt.js causing body parameters to not be passed successfully while using this.$http.post

I've encountered an issue where using the @nuxt/http this.$http.post and this.$http.patch methods is causing problems with parsing body parameters during posting. Strangely, it used to work perfectly fine before, leaving me unsure of where to even beg ...

Is there a way to rigorously validate my HTML, CSS, and JavaScript files against specific standards?

Can modern browsers suppress errors in HTML, CSS, and JS sources? Is there a method to uncover all mistakes, no matter how small they may be? ...

The initial update of the view does not occur when a component property changes in Angular 2 RC6

I am currently facing an issue with a component in my project. This component calls a service to retrieve locally stored JSON data, which is then mapped to an array of objects and displayed in the component view. The problem I am encountering is that the v ...

Visual Studio 2015 does not support compiling typescript files

I'm encountering some difficulties while attempting to set up node with typescript support in Visual Studio 2015 for my web API application. To start fresh, I deleted the node_module folder along with the package.json and tsconfig.json files. Followi ...

Enhancing elements with fade-in effects upon hovering

Is there a way to incorporate a subtle fade in/fade out effect when hovering over items on this webpage: http://jsfiddle.net/7vKFN/ I'm curious about the best approach to achieve this using jQuery. var $container = $("#color-container"), ...

Retrieving a value using forEach in protractor - Dealing with closures

I am facing an issue with the helper code below, as it is not returning the correct number of occurrences of a string. this.getActualFilteredStatusCount = function(strFilter){ return this.getTotalRows().then(function(count){ var totalCount = ...

The issue of Angular 15 Childcomponent failing to refresh the user interface despite input modifications

Within this component, I have two child components: <span>Timings:</span> <sir-project-fasetiming [faseTiming]="projectTiming.timingInitiatie" (faseTimingChanged)="faseTimingChanged($event, 'timingInitiatie')"&g ...

The code below is not working as it should be to redirect to the home page after logging in using Angular. Follow these steps to troubleshoot and properly

When looking at this snippet of code: this.router.navigate(['/login'],{queryParams:{returnUrl:state.url}}); An error is displayed stating that "Property 'url' does not exist on type '(name: string, styles: AnimationStyleMetadata". ...

The console log is displaying 'undefined' when trying to access Node.js fs

Recently, I was engrossed in developing a Next.js blog. After completing the frontend, I shifted my focus to building the backend using Next.js. ./pages/api I created a new file: ./pages/api/blogs.js To test my backend functionalities, I generated some J ...

Is Webpack bundling the node_modules of node_modules into the bundle?

Recently, I noticed that webpack is bundling dependencies from the top-level node_modules directory into my actual bundle. For instance, one of my dependencies, example-dep, relies on lodash and has a nested node_modules directory at node_modules/example-d ...