AngularJS: Tips for Waiting in the 'Run' Method until Completion

I am facing a simple issue - I want to set up my http calls with an interceptor that will include a token in the headers. The challenge is that the token is received through an http call as well (which should be the initial call), and I'm unsure how to ensure that all subsequent calls wait for this process to complete before making their own requests...

.factory('sessionData', function () {
    var currentToken = '[uninitialized-token]';
    return {
        getToken: function () {
            return currentToken;
        },
        setAuthData: function (token) {
            currentToken = token;
        }
    }
})
.factory('sessionInjector', ['sessionData', function (sessionData) {
    var sessionInjector = {
        request: function (config) {
            console.log("sending with token: " + sessionData.getToken());
            config.headers['x-header-sessionID'] = sessionData.getToken();
        }
    };
    return sessionInjector;
}])

.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.push('sessionInjector');
}])

.run(['$http', 'configs', 'sessionData', function ($http, configs, sessionData) {
    $http.get(configs.authApiUrl + 'login').then(function (ret) {
        sessionData.setAuthData(ret);
        console.log("successfully authenticated with token " + sessionData.getToken());
    });
}])

.controller('TestCtrl', function($http){
    $scope.p1 = 'Uninitialized';

    $http.get('http://localhost/api/getData').then(function(ret){
        $scope.p1 = ret;
    });
});

The issue here is that the TestCtrl triggers an http request before the completion of the run method, resulting in the header value containing the [uninitialized-token].

How can we make sure that the controllers wait for the asynchronous 'run' methods to finish?

Answer №1

Using $http interceptors in Angular allows you to utilize promises in their callbacks, enabling you to intercept each API call and delay it until the promise is resolved.

A solid grasp of how promises function is essential for implementing this feature effectively.

For instance:

myModule.factory('tokenPromise', function($http) {
    return $http.get({url: 'myurl/token', bypassToken: true}).then(function(data) {
         // Handle the response from your token webservice here
         return data.token;
    });
});

myModule.factory('myHttpInterceptor', function($q, tokenPromise) {
  return {
    'request': function(config) {
      if (config.bypassToken) return config;
      // Make sure the token promise is resolved before continuing with the request.
      return tokenPromise.then(function(token) {
         config.headers['x-header-sessionID'] = token;
         return config;
      });
    },
  };
});


myModule.config(function($httpProvider) {
     // Register the interceptor here
     $httpProvider.interceptors.push('myHttpInterceptor');
})

Reference: Official documentation on Angular's HTTP service

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

What is the best way to display a component based on a certain condition?

There are two instances where the Items component needs to be displayed. However, in one instance an additional component, Filters, is required while in another it is not. The Filters component is nested inside Items. When attempting to implement this, ...

Improving the efficiency of my conditions in a function with Vue JS

Does anyone have any suggestions on how to optimize this function? I feel like it could be shortened to improve its efficiency. Any help or advice would be much appreciated. Function: onStudentActionSelect: function () { if (this.selectedRows.length ...

Add a message displaying the error in the input field using jQuery Validation

Is there a way to append the jQuery Validation error messages to the input field or get help with positioning them properly? The random popping up of error messages is causing chaos in the form layout. I prefer to have the error messages displayed undern ...

HTML: Body with a larger height than its actual content dimensions

My Chrome browser extension seems to have a body that is much taller than its actual content: https://i.sstatic.net/t44t6.pnghttps://i.sstatic.net/8WjzD.png Even though there are no other parent div elements, the height of the <div id='app'& ...

Swapping out the title attribute within imgbox

After updating to the latest version of imgbox, I encountered a similar issue as I did with LightBox2 involving the 'title' attribute. It creates a caption, but the HTML tends to show a hovertext over the image link. Here is an example: <a ...

The function defineCall does not exist, causing a sequelize error to occur

A challenge I've been facing is resolving an error that is popping up in my index.js file. I'm currently utilizing Node, Express, and sequelize in my project. /app/node_modules/sequelize/lib/sequelize.js:691 server_1 | this.importCache ...

How can CORS be activated? Is it through the server or Javascript, and where does this

Currently, I am testing my ReactJS website on localhost:3333 and my ASP.NET Web API 2 on localhost:54690. I am utilizing axios for my AJAX requests, but encountering an error when making a request. XMLHttpRequest cannot load http://localhost:54690/api/ ...

using the useEffect hook to create a loop that runs infinitely

For my project, I am working on updating data in firebase. The issue that I'm facing is that the data seems to be constantly looping, causing potential crashes. Is there a way to stop this loop and prevent any crashing? import "./App.css"; ...

`"Unable to execute the 'ng build --env=prod' command"`

I have a JavaScript website that I need to rebuild with some changes I made. In order to build the application, I was instructed to run this command from the source files directory: ng build –env=prod However, when I try to do so, I keep encountering t ...

Issue detected: The validation form is encountering errors due to a blank textarea when utilizing jQuery validate and AJAX for

I am currently working on a spring project that involves registering comments on a specific system design. The page layout for this task is as follows: <form id="formularioCadastroComentario" role="form" method="POST" class="form-horizontal"> &l ...

How can we effectively reroute HTTP requests according to the information stored in a database?

When operating an express server, what is the appropriate method for redirecting incoming requests? In my application, I have two routes: POST and UPDATE. The POST route is responsible for creating a new item in the database, while the UPDATE route increa ...

Utilizing a switch statement for efficiently loading multiple objects within a Three.JS framework

Currently, I am working on a web 3D model viewer that utilizes Three.JS. My goal is to enable users to select different models from a dropdown list using dat.GUI. To achieve this, I have been experimenting with a switch statement, drawing inspiration from ...

Preserve a retrieved value from a promise in Angular

Upon loading the page, the dropdown menu is populated with various values (such as 1, 2...7). However, when attempting to set a specific value based on a certain condition within a promise, it doesn't seem to work. How can this issue be resolved? htm ...

I am looking for a tool that can extract XML data from a remote URL and convert it into JSON format for easy retrieval using JavaScript

Grabbing XML directly from your own domain's local URL is simple, but doing so cross-domain can be more challenging. How can you retrieve the XML data located at using javascript? ...

What is the most effective way to inform the user when the nodeJS server can be accessed through socketIO?

I have developed a web app that indicates to the user when the server is online for data submission. Although the current code functions properly for single-user interaction, I am facing an issue where one user's connection or disconnection directly i ...

Angular Digest Loop for Dynamic Photo Grid Styling

I have a special filter that alters the objects being filtered. However, when I apply ng-style="item.gridSize", it triggers my custom grid algorithm. This algorithm was adapted for my requirements from a source found at this link. angular.module("custom.m ...

Storing data using Ionic Local Storage - easily save your $http database directly onto your

I have encountered a problem with the local storage in my Ionic app. The concept is simple - I want to save all the data from an SQL database to the device and then display it when there is no internet connection. Here is the code snippet where I fetch th ...

When attempting to perform conditional rendering in React using a stateless functional component, I encounter an error stating "Unexpected token, expected ,"

Here is the code snippet: 'use strict' import React from 'react' import { connect } from 'react-redux' import { Panel, Col, Row, Well, Button } from 'react-bootstrap' const Cart = ({ cart }) => { const cartI ...

Utilizing JSON data from Jade in local JavaScript: A comprehensive guide

Attempting to utilize a JSON object (the entire object, not just a portion) from Node via Jade in my local myScript.js. Here is what my Jade file looks like: span(class="glyphicon glyphicon-pencil" onclick="confirm(\"#{myJSON.taskid}\", \" ...

Continuously improving the form as they evolve

I am interested in creating a form that automatically sends data when users make changes to it. For instance: Imagine a scenario where a moderator is editing an article and changes values in a select field. As soon as the change is made, an ajax request ...