AngularJS initiates an XMLHttpRequest (XHR) request before each routeChange, without being dependent on the controller being used

I'm currently embarking on a new project, and for the initial phase, I want to verify if the user has an active session with the server by sending an XHR HEAD request to /api/me.

My objective is to implement the following syntax

$rootScope.$on("$routeChangeStart", function(event, current, previous, rejection){/*...*/})

The dilemma lies in not wanting to duplicate this code for every controller. Is there a way to achieve this in a more universal manner?, .run?, service(factory), what would be the best approach?.

If possible, provide a simple code snippet since I'm fairly inexperienced with this framework.

var app = angular.module('home', []);
var httpConfig = {withCredentials: true};
app.config(function($routeProvider){
$routeProvider.
when('/', 
    {
        template: 'views/home.html', 
        controller: homeCtrl 
    }).
when('/login', 
    {
        template: 'views/login.html', 
        controller: loginCtrl 
    }).
when('/logout', 
    {
        template: 'views/logout.html',
        controller: logoutCtrl

    }).
otherwise(
    {   
        template: 'views/home.html', 
        controller: homeCtrl
    })
}).
run(function($rootScope, authUser){
    $rootScope.$on('$routeChangeStart', function () {
        authUser($rootScope);
    })
}).
factory('authUser', function($http, httpConfig){
    var promise = $http.head('/users/me', httpConfig);
})

Answer №1

If you want to implement $routeProvider resolve, you can follow this example:

app.config(function($routeProvider){
$routeProvider.
 when('/', 
{
    template: 'views/home.html', 
    controller: homeCtrl,
    resolve:{auth:"authUser"}
}).
when('/login', 
{
    template: 'views/login.html', 
    controller: loginCtrl ,
    resolve:{auth:"authUser"}
}).
when('/logout', 
{
    template: 'views/logout.html',
    controller: logoutCtrl,
    resolve:{auth:"authUser"}

})

Make sure your factory function returns a promise like so:

app.factory('authUser', function($http, httpConfig){
    return $http.head('/users/me', httpConfig);
})

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

Adjust the size of the text within the div element as needed

Here is my code on jsFiddle where I am dynamically changing the text font to fit in the div. Everything is working perfectly fine. Currently, the text is within a span element, but I would like to remove the span and have the same functionality. However, w ...

Having issues with a local image not loading in React?

I am trying to display a local image in React js. After referring to this solution, I have tried the following code - <img src={require('../public/images/icon.png').default} /> The image "icon.png" is stored in my public folder, and I&apos ...

what is the best way to center list items in material ui?

I have been attempting to align the list items (checkbox, text, and buttons) within a Material UI list in the center, but all my attempts have been unsuccessful. Is there anyone who knows how to resolve this issue? Your help would be greatly appreciated! h ...

Applying a custom class to a particular row in an AngularJS datatable using the created

I am currently working with AngularJS datatables and I want to apply a custom class to a row if a specific condition is met. Here's what I have attempted so far: this.dtOptions = DTOptionsBuilder.newOptions() ... .withOption('createdRow', f ...

What is the best way to make IE 10 display a pointer instead of an I-bar for a select list?

Is there a way to make IE 10 display a pointer instead of an I-bar when selecting from a list? Despite trying various methods found in similar questions, I have been unable to resolve this issue. The cursor: pointer property works as expected on other br ...

Utilizing Jquery for Enhancing Annotations

I am in the process of developing a website for essay writing tests. I have implemented a feature where users can input their essays using a text area, and now I want to be able to make comments on that text similar to PDF annotations or highlighting. I at ...

Ensure that an input field on the PHP form is required

Currently working on a form with multiple input fields. I'm wondering if there's a way to prevent the form from being submitted to the server if a specific field is left empty. I'd like to use a JavaScript pop-up box to notify the user inst ...

Using Slick.JS to Sync Navigation with Main Slider, Automatically Resetting to First Slide

I have a question about the functionality of the Slick.JS plugin that I'm using. In my project, I have two carousels with five slides each. The top carousel displays one slide at a time, while the bottom carousel shows all five slides concurrently. My ...

"Performing validation on a number input by using the ng-change event

Im using a number input that dynamically sets the min and max values based on another form field. I have two scenarios: Level 1: Min = 2, Max = 50 Level 2: Min = 5, Max = 1000 I've set up an ng-change event on the input field to check if the entere ...

Having trouble locating the name WebGLObject in my TypeScript code

Every time I try to run ng serve command An error pops up on my screen saying: "WebGLObject cannot be found." ...

In some cases, ui-router may fail to navigate to a different page on Internet Explorer versions greater than 9

Currently, I am utilizing ui-router for my application. Interestingly, in Internet Explorer versions above 9, the page routing functionality seems to cease working at times. This issue is particularly prominent when I manually modify the URL path and pre ...

Tips for making sure the Button component in material-ui consistently gives the same ID value for onClick events

Issue arises when trying to log the ID of the Button component, as it only logs correctly when clicked on the edges of the button (outside the containing class with the button label). This problem is not present in a regular JavaScript button where text is ...

Identify when the Vue page changes and execute the appropriate function

Issue with Map Focus Within my application, there are two main tabs - Home and Map. The map functionality is implemented using OpenLayers. When navigating from the Home tab to the Map tab, a specific feature on the map should be focused on. However, if th ...

How the logo's placement shifts while zooming out (using CSS and Angular 4+)

I am facing an issue with my navbar that includes a logo (MostafaOmar) which shifts position when zoomed out. If you try zooming to 70%, you will notice the logo's position changes as well. Is there a way to make it stay in place at 100% zoom? Here ...

Position a dynamic <div> in the center of the screen

My goal is to design a gallery page with a list of thumbnails, where clicking on a thumbnail will open the related image in a popup div showing its full size. The issue I'm facing is how to center the popup div on the screen, especially when each pic ...

Try utilizing the array find() method in place of a traditional for loop

Is there a better way to refactor this code using the Array.find() method instead of nested for loops? onLoadTickets() { const ticketsReq = this.ticketService.getTickets(); const tariffsReq = this.tariffService.getTariffs(); forkJoin([ticketsR ...

Cypress OPENSSL_internal:NO_START_LINE error detected

Has anyone encountered this error before? I've already tried clearing the cypress cache and reinstalling it, but the error persists. I couldn't find a solution to resolve this issue. The version I am using is 6.5.0. Error: error:0900006e:PEM rou ...

Need to know how to invoke a function from an http callback function that resides in a separate file? Simply use the `app.get("/", callbackFun)` method

Directory Organization: testAPI contactDetail dispMobNo.js myModule.js index.js index.js const express = require("express"); const app = express(); const port = process.env.port || 3000; const getCustNo = require("./cont ...

Maintaining a reference to an element while binding event handlers in a prototype

Is there a way to utilize a bound event handler in prototype while maintaining the "this" context? It seems that doing so disrupts the default binding provided by prototype for event handlers. According to the documentation: The handler's context ...

Angular event triggered when updating input values from the model

I have developed a custom directive to add functionality to input fields with a specific class. I want to trigger events on blur and focus to update the label style based on Material Design principles. However, when using ng-model in Angular, I also need t ...