Angular updates location, but browser redirects to incorrect page

I want my application to redirect non-logged in users to a login page. Following advice from a popular source, the app listens for routeChangeStart events like this:

$rootScope.$on("$routeChangeStart", function(event, next, current) {
    if ($rootScope.currentUser === null) {
        var allowPublic = ["partials/logIn.html", "partials/start.html"];
        var allowed = _.contains(allowPublic, next.templateUrl);
        if (!allowed) {
            $location.path("/logIn").replace();
        }
    }
});

Although this logic functions correctly, changing $location.path does not seem to have any effect. The URL changes to /logIn in the browser's address bar, but the view still displays the unauthorized content. Any ideas on what might be causing this issue?

My routes are defined as follows:


$routeProvider.when('/start', {templateUrl: 'partials/start.html', controller: 'StartController'});
$routeProvider.when('/logIn', {templateUrl: 'partials/logIn.html', controller: 'LogInController'});
$routeProvider.when('/restricted', {templateUrl: 'partials/restricted.html', controller: 'RestrictedController'});

In certain instances, the start page controller attempts to navigate to the restricted page like so:

// within StartController
$scope.pressedButton = function() {
    $location.path('/restricted');
    // I would like to handle this and redirect based on previous logic if user is not logged in
};

Answer №1

If someone happens to stumble upon this post in the future, here's what I ended up doing, even though I still don't completely grasp why it resolved the issue. Essentially, the solution involved encasing the location change within a timeout function.

        if (!allowed) {
            $timeout(function() {
                $location.path("/logIn").replace();
            }, 0);
        }

I believe the problem stemmed from my code attempting to alter the location while simultaneously monitoring for changes in location, resulting in a regression (which gets interrupted once the second call is made to an authorized location). By using $timeout to wrap the path modification, I assume I am allowing the initial location transition to complete before initiating the redirect.

While I'm not entirely certain about this explanation, I reached this conclusion after referring to the "Triggering Events Programmatically" segment mentioned in this Angular documentation.

This approach seems logical, but it leaves me wondering why many of the route security solutions I came across didn't highlight this potential pitfall. (For example, reference the highly acclaimed response here).

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

Encountered an error when attempting to submit with Node.js and Express.js connected to MySql - "Cannot POST /login

I am currently working on creating a basic login page using node.js with the express.js and mysql packages. The goal is to redirect users to the layout.html page if their username and password exist in the mysql database. For this project, I have set up a ...

Using Node.js crypto for the cryptoMd5Method in EvaporateJS: A step-by-step guide

In my React project using webpack, I have integrated EvaporateJS for file uploads. Following the instructions in the documentation, I added the following code snippet: (I opted not to use aws-sdk due to its large package size, although it functioned corr ...

What are the steps to implement an audio stream in a JavaScript React application?

I have been working on integrating a web dialer system into my JavaScript NextUI React app. After making some progress, I can successfully dial and hear my voice through the phone. However, I am encountering an issue where I cannot hear the other person sp ...

Express middleware for handling errors with Node.js router

My application structure is laid out as follows: - app.js - routes ---- index.js The ExpressJS app sets up error handlers for both development and production environments. Here's a snippet from the app.js file: app.use('/', routes); // ro ...

Variables for NPM Configuration

After researching the best way to securely store sensitive information, I decided to utilize the config package and environment variables for added security. Here is how I implemented this setup: Created a config directory containing two files: default.js ...

tracking scroll position within div on main page

I have a div tag enclosed within a content tag due to the implementation of a masterpage containing the forms and body tags. <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server"> <div id="xxx" style="overflow:s ...

Issues detected between Angular and Express rendering operations

Having an issue with my angular code. It runs perfectly on its own, but when I try to access it on localhost with express, it only displays the HTML file. Here's my server code: var express = require('express'), app = express(); app ...

Issue with NodeJS SQL Login: Received error (ERR_HTTP_HEADERS_SENT): Headers cannot be set after being sent to the client

Hi there, I am fairly new to working with nodeJS and I have encountered an issue that I suspect lies within the second if statement inside "db.query..." in the code provided below. An error message showing ERR_HTTP_HEADERS_SENT]: Cannot set headers after ...

Creating a stunning art exhibition using React Native

Currently, I am in the process of creating a gallery component that utilizes both the scrollview and image APIs. I'm curious about how the scrollview manages its child components when it scrolls down. Does it unmount the parts that are not currently ...

Pass information from a row to an AngularJS controller upon clicking the checkbox within the row

I need help with some HTML code that utilizes AngularJS to display a table. Each row in this table contains a checkbox. Here is a snapshot of the table layout: https://i.sstatic.net/ibDor.jpg Below is the actual HTML code: <div ng-app ng-controll ...

What is the best way to manage sessions in angularjs using javascript?

Only at two specific instances in the application should the login prompt be displayed: When trying to access a page that requires login while not logged in, such as my profile page. When attempting an action that necessitates ...

When refreshing the React page, it appears blank

Encountering a issue with one of the pages on my react website. Whenever I attempt to reload the Home.js page by refreshing the browser, it displays blank. However, when using the back navigation button in the browser, it functions correctly. I've che ...

Unable to create a polygon on the Google Maps API using GPS coordinates inputted from a text field

I am currently developing an interactive map using the Google Maps API. The map includes a floating panel with two input fields where I can enter GPS coordinates. My goal is to create markers and connect them to form a polygon. While I can easily draw lin ...

Is your webpage slow to respond after a page-refresh? (Delayed HTML rendering causing lag)

Whenever I adjust the screen size to that of a phone or any device smaller than 768px, the search bar doesn't display in its proper position until the page is refreshed. It should be correctly placed right from the start. Furthermore, when I resize th ...

Ajax requests function properly only on one occasion

My select option works perfectly the first time, but then the request does not execute again. I suspect that the issue lies with the 'onchange' event. Here is my Ajax code : jQuery(document).ready(function($) { $('#referenceProduit') ...

Utilizing ACE editor in conjunction with Angular for dividing the input by new lines

I have successfully integrated the ACE code editor into my application using the ace-ui directive with angular. Overall, it has been working well, but there is one issue I am facing. I want the code written in the editor to be stored as an array of string ...

Safely render user-generated HTML content within a React application to prevent cross-site scripting vulnerabilities

A unique situation has arisen in our React app where a user inputs a string that is displayed to other users. The challenge lies in searching for specific characters within the string and replacing them with HTML elements. For example, transforming the wor ...

What is the best way to incorporate AngularJS into an MVC view and transfer information to an AngularJS controller?

I am facing an issue with my AngularJS MVC application where it posts a form to a different domain and receives a callback as a plain HTTP post to the MVC controller function. However, when the view is loaded after the callback comes back, the AngularJS co ...

Alternating the tooltip icon based on the field's condition

Looking for a way to create a tooltip for an input field that involves changing icons based on certain conditions. An example scenario is the password field in a registration form. Seeking advice on the best approach to achieve this. Currently, here' ...

Checking for correct format of date in DD/MM/YYYY using javascript

My JavaScript code is not validating the date properly in my XHTML form. It keeps flagging every date as invalid. Can someone help me figure out what I'm missing? Any assistance would be greatly appreciated. Thank you! function validateForm(form) { ...