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

Utilize ngFor in Angular Ionic to dynamically highlight rows based on specific criteria

I'm working on an application where I need to highlight rows based on a count value using ngFor in Angular. After trying different approaches, I was only able to highlight the specific row based on my count. Can someone please assist me? Check out m ...

Designing a user interface that consists of numerous distinct components

Challenge I'm faced with a dilemma regarding site A, which is built using React. Specifically, I need to find a way to integrate smaller React components into site A whenever a user navigates to a specific page within the site. Each of these smalle ...

When a page loads, automatically refreshing a row in MySQL

I've been searching around, but haven't found a solution to my basic issue. I need help with creating a system where a user can only view a page once per day. Currently, clicking a button updates the MySQL Row, but users can bypass this restricti ...

Is there a way to prevent the Pace js plugin from running on page load, but still have it execute during Ajax requests only?

I have successfully implemented the jquery pace plugin with a progress bar theme. Everything is working well, but I am looking to make it run only on ajax requests. I have tried various solutions found through research, but haven't had any luck. Belo ...

Having trouble changing the Font Awesome icon on click?

I'm struggling to figure out why I can't change a font awesome icon using a toggle. I've tried various solutions but nothing seems to be working. Any insights on what might be causing this issue? (HTML) <span class="toggle-icon" ...

Utilize jQuery and AJAX to refresh functions after each AJAX call for newly added items exclusively

I have encountered an issue with my jQuery plugins on my website. Everything functions smoothly until I load new elements via AJAX call. Re-initializing all the plugins then causes chaos because some are initialized multiple times. Is there a way to only i ...

Transferring an Excel file through an HTML form input to a Java REST method

How can I submit an excel file from an HTML form input field and send it to a RESTful Java method for processing? I am integrating AngularJS into my project as well. ...

What are the primary purposes of the site.webmanifest file?

As I navigate through an HTML Boilerplate, I come across a file named site.webmanifest. Despite my efforts to research its purpose online, I am still unclear about its significance. Could this file be essential for website development? What are the specif ...

Preventing links from functioning on dynamically generated web pages

I have implemented the following code to deactivate all links on a preview page: var disableLink = function(){ return false;}; $('a').bind('click', disableLink); While this successfully disables all static links, any anchor tags loade ...

Jest - Silence greets the test results

Struggling with Jest has been a common theme for me ever since I first attempted to use it. Regardless of the tests I run or the options I try to pass to Jest, I never seem to get the expected 'Pass' or 'Fail' results in the console. In ...

Upload files via Ajax request is required

I am in the process of trying to upload a binary file to a server while avoiding a full page refresh when the server responds. I must admit, I am not well-versed in this area and I understand if my approach needs some adjustments. This is how I have appro ...

Delete items within the first 10 minutes of shutting it down

Is there a way to temporarily remove a newsletter element for 10 minutes after closing it on a webpage? The idea is that once the panel is closed, it should stay hidden even if the page is refreshed within that timeframe. I was considering using local stor ...

What is the process for adjusting the expiration time of a GitLab accessToken?

I am currently using NextAuth for logging in with GitLab, but I am encountering an issue where my accessToken changes every 2 hours. How can I ensure that it remains valid for a longer period so that I can successfully store it in my database? It's wo ...

Ways to integrate AngularJS into your x-cart platform

Recently, I've been working on x-cart which utilizes the Smarty template engine. My client has requested to integrate angularjs into x-cart, but despite numerous attempts, I have not been successful in implementing it. After researching extensively on ...

What is the best way to access the image source attribute within a directive?

Here's a straightforward image directive example: (function () { 'use strict'; angular .module('myapp') .directive('imageTest', imageTest); function imageTest() { var directive = { ...

Creating a user-friendly form with validation in a Vue application using Vuetify.js

I am in the process of incorporating a contact form with basic validation on a Vue.js website using an example from Vuetify.js. Being new to this, I'm unsure about how to implement it within a Vue component. My goal is to have simple client-side form ...

Problem: The variable "$" is not defined in angular datatables causing a ReferenceError

Trying to implement Paging and sorting in my table, but encountered an error even after following all the steps mentioned here: . Tried troubleshooting the issue with no success. Ensured that all dependencies were installed properly. Below is the compo ...

Leverage the Google Drive API for the storage of app-specific data

I'm currently developing a JavaScript application that runs on the client side and need to store a JSON object containing configuration details in a Google Drive Appdata file. Through the Google Drive API, I can successfully check for the file within ...

Adjust the left margin to be flexible while keeping the right margin fixed at 0 to resolve the spacing

To create a responsive design that adjusts based on screen size, I initially set the content width to 500px with a margin of 0 auto. This meant that for a 700px screen, the content would remain at 500px with left and right margins of 100px each. Similarl ...

Creating numerous pre-signed URLs using an Application Programming Interface

An API has been developed to generate pre-signed URLs for files stored in a private S3 bucket. The goal is to store these URLs in an array for access from another application. ["FILE1 pre-signed URL", "FILE2 pre-signed URL", etc..] However, there seems to ...