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

Angular JS Changing Values in a Dynamic List

Creating Dynamic HTML with Angular Directives I'm working on code that generates HTML dynamically and includes Angular directives. Since these directives are late-bound, I need to ensure they execute and generate their respective template contents. I ...

Tips for implementing a controlled RadioGroup in React: Mapping through an array of values to dynamically populate radio buttons

I have a scenario where I am utilizing a pre-defined set of arrays to populate multiple RadioGroups. The component hierarchy in the codesandbox is structured to resemble that of my actual project. Whenever I select a radio button, I receive an error messa ...

Utilizing Freebase Suggest, is there a way to refine a field by the choice of another field?

When utilizing Freebase Suggest (), and having a field that chooses between Country or State, how can I make another "City" field filter to only display cities within that selected Country or State? In addition, if a user selects "New York" as their State ...

Struggling to get the jQuery resize event to function properly

Ensuring that my charts remain responsive on different devices has been quite a challenge. Despite implementing a resize event handler in my function to dynamically adjust the charts, I encountered an issue where the page would go blank upon resizing the b ...

React Native ScrollView ref issue resolved successfully

I'm trying to automatically scroll to the bottom of a flatlist, so here's what I have: const scrollViewRef = useRef(); //my scroll view <ScrollView ref={scrollViewRef} onContentSizeChange={() => { scrollViewRef.current.scr ...

JavaScript function is not identifiable

I am currently developing a tic-tac-toe game with 9 buttons that will display either an X or O image depending on the boolean value of the variable isX. The main container for these buttons is a div element with the id 'stage' and each button ha ...

Generating a fresh document in MongoDB using Mongoose, complete with references and assigned ObjectIDs

I've been attempting to use the mongoose create function in order to generate a new document with references, but I'm encountering an error when trying to provide objectIds for those refs. Despite my efforts to find a solution, I have been unsucc ...

What could be the reason for the function providing the value of just the initial input?

Why am I only getting "White" when I click on the colors? I can't seem to get any other values to appear on the screen. I'm confused about what mistake I might be making here. var x = document.getElementById("mySelect").value; function myFunc ...

Ways to update state based on changes in localStorage values

Is there a way to update the state when the value of localStorage changes? For instance, I have a language switch button for French and English. When I click on English, it gets stored in localStorage. How can I ensure that the entire project switches to t ...

What is causing the table to not be displayed in this Javascript program when it is used in a

I am currently experimenting with incorporating an infinite loop before the prodNum and quantity prompts to consistently accept user input and display the output in a table. Although the program is functional when executed, it fails to showcase the table ...

Tips for displaying content when clicking on the opener containing tables or div elements

This is a snippet of JavaScript code $(document).ready(function () { $(".show-content").hide(); $(".opener").click(function () { $(this).parent().next(".show-content").slideToggle(); return false; ...

Custom Select Menu Options from Basic Key-Value Mapping

There are other answers that discuss using ng-option with an object structure like this: $scope.opts = [ {value: 111, text: '1st' }, {value: 222, text: '2nd' } ]; However, I am curious if it is possible to achieve the same functi ...

Tips for configuring Webstorm to automatically change double quotes to single quotes when reformatting source code

After using cmd + alt + l in Webstorm to format my JavaScript code, I noticed that double quotes are used instead of single quotes. How can I configure Webstorm to automatically change the double quotes to single quotes in my code? ...

The command 'ng' is not a valid internal or external command, and it cannot be run as an operable program or batch file on the Mean Stack platform

Hey there, I'm in the process of developing a meanstack application. Every time I try to run 'ng new client' command, it gives me an error saying 'ng' is not recognized as an internal or external command, operable program or batch ...

changing the css transformation into zoom and positioning

My goal is to incorporate pinch zoom and panning using hardware-accelerated CSS properties like transform: translate3d() scale3d(). After completing the gesture, I reset the transform and switch to CSS zoom along with absolute positioning. This method ensu ...

Laravel throws an error message "expression expected" when trying to use the @

I keep encountering an issue when attempting to pass a variable from PHP code to JavaScript. Expression expected Here is the code snippet I am using in Laravel 7.0 : <script> let variable = @json($array); </script> Although the code still ...

Getting the Value from a Promise into a Variable in a React Component

I am currently immersed in a React project where I am utilizing the Axios library to retrieve data from an API and store it in a variable. After scouring the internet, it seems that the only method available is through Promise.then(), but this approach si ...

Function for testing global variable stub in JavaScript

Currently, I am in the process of writing Unit tests for a React application. Within the page header, the tracking library 'mixpanel' is inserted between <script> tags as outlined in their documentation: . The documentation states that "Th ...

Prevent redundant Webpack chunk creation

I am currently working on integrating a new feature into my Webpack project, and I have encountered a specific issue. Within the project, there are two entry points identified as about and feedback. The about entry point imports feedback, causing both abo ...

Setting up parameters and arguments in Vuex mutations: A guide

I am currently developing a todo list application using Vue.js, Vuex, and Firebase. The functionality of the app seems to be in working order with the Store file effectively managing the retrieval and display of entered todo items to and from Firestore. Ho ...