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

What could be causing React to throw an error?

Check out this React Component: GeneralInformation = React.createClass({ totalCaptialRaisedPanel: function() { var offeringInfo = this.props.company.data.offerings.data[0]; var percentageComplete = (offeringInfo.capital_raised / offer ...

Here is a guide on how to develop a PHP function that interacts with a textarea to display text in the specified color by using syntax like [color:red]

Is it possible to code a PHP function that can work alongside a textarea to display text in the specified color by using a syntax like [color:red]? This function operates in a similar manner to Facebook's @[profile_id:0] feature. ...

The jQuery script is functioning flawlessly in one specific direction

Currently, I am utilizing a basic script to alter the color of elements based on the div being hovered over. While this works smoothly in one direction down the line, when trying to reverse order and backtrack, the colors do not function as intended. The ...

Dynamic autocomplete feature with AJAX integration for filtering in Flask

Looking for some guidance on creating an HTML form with two input fields. Check out the HTML template code below: <form role="form" action="/cities/" method="get" autocomplete="on"> <label for="#input1"><strong>Country:</strong&g ...

Learn how to implement pagination in AngularJS using the $http service

I need assistance in implementing pagination using Angularjs within the Ionic Framework. Can someone provide guidance on how to code pagination for fetching data from a JSON URL? controller.js angular.module('starter.controllers', []) .control ...

ng-click activating every item within ng-repeat loop

I am facing an issue where clicking a link in one of the items within ng-repeat triggers all the links in the ng-repeat section. I have looked at similar questions for help but couldn't find a solution. Here is the Plunker for reference: https://plnk ...

What is the way to execute a function *once* all my ajax call functions have finished?

I am utilizing jQuery to execute some ajax requests: var information = {}; function process_information(item){ information[item.id] = item; } function perform(){ var calls = []; for(var i = 0; i < 10; i++){ var call = $.get(URL, ...

I must only assign the result to "value" if the condition of the map is true

I am looking to set the variable "value" to only contain the value that meets the condition in the map function const arr= [1,2,3,4,5]; value = arr.map(item => item > 4 && item) console.log(value); The resulting value is currently [false, false, fa ...

Is there a way to verify the selection of all mandatory fields prior to concealing a div?

var count = 2; $('.next').click(function() { var requiredField = true; $(this).siblings('table').find('tbody tr:nth-child(' + count + ') td').each(function() { var element = $(this).find('center').f ...

ESLint detecting error with returning values in async arrow functions

Currently facing a minor inconvenience instead of a major problem. Here is the code snippet causing the issue: export const getLoginSession = async (req: NextApiRequest): Promise<undefined | User> => { const token = getTokenCookie(req) if (!t ...

Upon page refresh, products are automatically added to the cart

While developing a shopping cart code, I encountered an issue where refreshing the page automatically added a product to my cart without any action from me. For instance, my website displays three products: Apple, Banana, Orange. When I click on Apple, it ...

Tips for adjusting image and div sizes dynamically according to the window size

In my quest, the end goal is to craft a simplistic gallery that closely resembles this particular example: EXAMPLE: This sample gallery is created using Flash technology, but I aim to develop mine utilizing HTML, CSS & Javascript to ensure compatibil ...

Arrange the given data either by ID or Name and present it

Here is the code snippet I am working with: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <style> .content{ border: 1px solid gray; width: 250px; ...

The FaceDetector within the expo application continues to activate the "onFacesDetected" event in "accurate" mode unnecessarily, even when no face is present

Just starting out with react native and I've been exploring the use of expo FaceDetector for detecting faces. In "fast" mode, the "onFacesDetected" event is triggered correctly. However, when switching to "accurate" mode, the "onFacesDetected" event k ...

Save a PNG file using the HTML5 Canvas when the Submit button is clicked, with the help of PHP

I am looking for assistance with a signature capture form. I came across a standard template on Github that works perfectly, but I wanted to customize it further. However, my Javascript skills are still in the early stages. The current code allows you to c ...

Is PhantomJS or prerender.io still necessary for crawling websites?

I am currently updating a project where I have switched to using AngularJS on the frontend. However, I encountered an issue with serving pages to crawlers. We do not use Akamai locally, but it is implemented on staging and production (using the old stack). ...

Having trouble with importing a TypeScript class: encountering a "cannot resolve" error message

Could you lend me your expertise? I'm puzzled by this issue that seems to be quite simple and straightforward: export class Rectangle { height: number = 0 width: number = 0 constructor(height: number, width: number) { this. ...

Zingchart encounters issues when attempting to plot a CSV file containing over 10 columns

Situation: I want to create a Zingchart graph from a CSV file containing 37 columns. The header in the CSV file will be used as the legend for the graph. Issue: When I define less than 10 elements in the header (including the X-axis name), everything wo ...

Best event for Angular directive to bind on image onload

I'm currently working on incorporating this particular jQuery plugin into my Ionic application. Although I have a good grasp of creating an Angular directive to encapsulate the plugin, I am encountering difficulties in successfully implementing it. B ...

Creating a list in Angular.js using the ng-repeat directive to iterate through data from

Recently, I started my journey with Angular.js and encountered my first small hurdle. This snippet is from my hello.js file: function Hello($scope, $http) { $http.get('URL'). success(function(data) { $scope.response = data });} The resp ...