What causes Angular to redirect to the route but display the incorrect view?

There is a fundamental issue I have encountered while working with routes:

  1. I have multiple routes defined
  2. If the user is not authenticated, they are redirected to the login page

The problem lies in the fact that, on the initial display of the web app, the user appears to be correctly redirected in terms of the URI, but the displayed view is incorrect (it shows the default view).

If you prefer to see the issue in action, I've set up a jsbin here. You can view the result here.

Steps to replicate the problem:

  1. Load the page
  2. You will see 'needsAuth', indicating that the content of the 'needsAuth' view is displayed even though the URI contains 'login' (which should correspond to the 'login' view)
  3. Refresh the page
  4. This time you should see 'login', meaning the content of the 'login' view is displayed

The HTML code:

<!DOCTYPE html>
<html ng-app='app'>
<head>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular-route.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <div ng-view>
  </div>
</body>
</html>

Below is the javascript code:

var template = '{{vm.text}}';

angular
  .module('app', ['ngRoute'])
  .config(['$routeProvider', routes])
  .controller('needsAuthController', needsAuthController)
  .controller('loginController', loginController)
  .run(['$rootScope', '$location', registerRedirection]);

function routes($routeProvider){
  $routeProvider
    .when('/needsAuth', {
      controller: 'needsAuthController',
      controllerAs: 'vm',
      template: template
    })
    .when('/login', {
      controller: 'loginController',
      controllerAs: 'vm',
      template: template
    })
    .otherwise({
      redirectTo: '/needsAuth'
    });
}

function needsAuthController(){
  var vm = this;

  vm.text = 'needsAuth';
}

function loginController(){
  var vm = this;

  vm.text = 'login';
}

function registerRedirection($rootScope, $location){
  $rootScope.$on('$routeChangeStart', function(event, next){
    $location.path('/login');
  });
}

Upon initial load, there seems to be a discrepancy between the URI and the displayed content

However, upon refresh, everything functions as intended:

Am I making a mistake somewhere? If so, what is the correct approach to redirect users based on certain conditions?

[Edit]: It seems that Angular 1.2.26 behaves properly in this scenario, unlike Angular 1.3.2

Answer №1

Modification

function redirectUser($rootScope, $location){
   $rootScope.$on('$routeTransitionStart', function(event, next){
       $location.path('/login');
   });
}

In order to

function redirectUser($rootScope, $location){
   $rootScope.$on('$navigationChangeStart', function(event, next){     

                     ^ modify this ^    

       $location.path('/login');
   });
}

Ensure that your initial page load functions correctly.

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

AngularJS - linking a function to an isolated scope using '&', but failing to trigger on ng-click event

I have a parent directive that includes a controller setting a method on $scope. In the child directive, I attempt to access this scope method using &. However, when trying to use the ng-click inside the child directive, it does not activate the pare ...

Webpack development server is not recognizing changes to the SCSS files

I successfully compressed and compiled my JavaScript and SCSS files using webpack. The SCSS file is extracted by the 'extract-text-webpack-plugin' into an external CSS file. Below is the code snippet: var path = require('path'); var we ...

Having trouble notifying a json object following an ajax request

My project involves using a PHP file that contains an array with multiple values. Additionally, I have an HTML page that features a single input field. A listener is set up to detect changes in the input field. Once a change occurs, an AJAX call is trigge ...

organizing arrays with the structure name:url

I have a list of string URLs like "http://dom/image1.jpg","http://dom/image2.jpg" that I obtained from an API which returns only the links. However, the plugin I am using requires the array to be in a specific format: {image:"http://dom/image1.jpg"},{imag ...

Organize an array of JSON objects based on a specific key and eliminate any duplicated entries

I am grappling with the challenge of grouping an array of JSON objects by the id_commande attribute and eliminating any duplicates. I am finding it quite perplexing to figure out a solution to this issue without relying on a library like lodash. Ideally, I ...

Elevate Angular version 1.4 to the latest update

My current project structure is displayed in the image linked below. I am currently working on upgrading the project to a higher version. https://i.stack.imgur.com/noavm.png I would greatly appreciate any suggestions or advice on how to utilize ngUpgrade ...

What is the most efficient method in React for displaying an array as a table and wrapping every set of five elements with a <tr> tag?

Currently, I am working on rendering a table in React from an array of objects. My approach involves mapping the array to create table elements as shown below: var objects = response.data; var arrayOfTableElements = [] ...

Tips for utilizing innerHeight for a div during both window loading and resizing tasks?

I'm currently working on calculating the top/bottom padding of a div (.content) based on its height, and updating it upon loading and resizing the window. The goal is to have it centered nicely next to another div (.character) positioned beside it. I ...

The Vue mixin properties are devoid of content and lack reactivity

Could you please guide me in the right direction if this question has already been asked before? I really hope it's not a duplicate. I have a Vue application that is compiled using Webpack@NPM. In order to pass a property (roles) across all component ...

Vue - Error Message from Eslint Regarding Absence of Variable in Setup Function

Interestingly, the Vue.js documentation strongly recommends using the <script setup> syntax of the Composition API. The issue with this recommendation is that the documentation lacks depth and it conflicts with other tools (like eslint). Here is an e ...

Difficulty parsing data from a JSON file using JavaScript

My knowledge about AJAX and JSON is very limited. I am currently attempting to import the information from dealerData.json into my MVVM viewModel, however, 'data' keeps returning as undefined. $(function () { var object; $.ajax({ ...

Adjust SVG size as per parent container in AngularJS custom directive

I have a unique situation where I am integrating an angular directive into a dynamically-sized element. The directive itself is made up of an SVG which adjusts based on the size of the container. I am working on making sure the SVG automatically resizes an ...

Unable to retrieve object element in angular

weatherApp.controller('forecastController', ['$scope','weatherService','$resource','$log', function($scope,weatherService,$resource,$log){ var cnto =3; $scope.forecastholder = weatherService.holder; $scope ...

Using a custom font with Next.js and Tailwind: Font applied successfully but not displaying correctly

In my project with Next.js (9.4.4) and Tailwind.css (1.4.6), I am incorporating a custom font named SpaceGrotesk. To ensure its functionality, I stored the font files in public/fonts/spaceGrotesk, and then adjusted my configurations as below: // next.confi ...

Directive fails to trigger following modification of textarea model

There is a block of text containing newline separators and URLs: In the first row\n you can Find me at http://www.example.com and also\n at http://stackoverflow.com. The goal is to update the values in ng-repeat after clicking the copy button. ...

Unraveling the mysteries of this PHP-generated object

Need help with iterating over a JSON object generated by PHP code in response to a web service request. Looking for guidance on rendering sub-objects in a select list, especially those with value indexes. Can someone provide assistance on populating a sel ...

What's the best way to unpack the gzip data that Ajax sends to JavaScript?

Hello there! I've encountered an issue: PHP is sending compressed data using gzdeflate(): $string=gzdeflate($string,9); echo $string; In the browser, pako.js has been included and the following code is executed: var rsp=rst.responseText; rsp=pako.in ...

Can we use a switch statement instead of having multiple @Input()s in Angular?

When passing an attribute into my Angular component like this: <my-component myAttribute></my-component> I aim to modify a variable within the component that controls the CSS properties for width and height. To simplify, I have predefined at ...

Several controllers are currently inactive

I have encountered an issue with my code where there are two separate applications with two different controllers, but the second one is not running. Despite being in two different modules, I can't figure out why this is happening. <!DOCTYPE htm ...

Is it possible to determine HTML5 Context Menu Support using JavaScript?

While reviewing the Modernizr documentation, I couldn't find any information on creating a menu element and then checking its existence. However, I am concerned that even if the browser supports this, it may not support the type context. Do you have a ...