When $routeChangeStart is triggered, the location fails to locate the corresponding template

In my web application, I have an app variable associated with the module myApp. There are 3 pages: /login, /registration, and /. The behavior of $routeChangeStart is defined as follows:

  1. First, it checks if a global variable user is defined. If yes, it moves to step 4.
  2. If the user wants to go anywhere other than /login or /registration, it prevents default behavior using event.preventDefault(). It then checks for a valid session via cookie authorization. If authorized, it sets the user global variable and redirects the user to their desired page. If not authorized, it directs them to the /login page.
  3. If the user intends to visit /login or /registration, no action is taken in the scenario where there is no user variable and they wish to log in or register.
  4. If the user wants to access /login or /registration, it prevents default behavior with event.preventDefault() and instead redirects them to the home / page since the user already has a valid active session.

The logic seems to be functioning correctly, except when pressing F5 on the / page with a valid session cookie. In this case, the application fails to redirect to the correct template, resulting in a blank page. Interestingly, inserting anything other than / in the URL (e.g., /blah) resolves the issue.

Below is my app.js configuration:

(function () {
    angular.module("myApp", ["controllers", "services", "directives", "ngRoute"])
        .config(["$httpProvider", "$routeProvider", function ($httpProvider, $routeProvider) {
            $httpProvider.defaults.withCredentials = true;
            $httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';

            $routeProvider
                .when("/login", {
                    controller: "LoginController",
                    templateUrl: "app/partials/login.html"
                })
                .when("/registration", {
                    controller: "RegistrationController",
                    templateUrl: "app/partials/registration.html"
                })
                .when("/", {
                    controller: "MainController",
                    templateUrl: "app/partials/home.html"
                })
                .otherwise("/");

        }])
        .run(function ($rootScope, $location, $http) {
            $rootScope.$on('$routeChangeStart', function (event, next, current) {

                if (!$rootScope.user) {

                    if (next && next.$$route && (next.$$route.originalPath !== "/login" && next.$$route.originalPath !== "/registration")) {
                        event.preventDefault();

                        $http.get("http://localhost:8080/myapp/api/user?self=true")
                            .success(function (data) {
                                $rootScope.user = data;
                                $location.path(next.$$route.originalPath);
                            })
                            .error(function () {
                                $location.path("/login");
                            });
                    }
                }else{
                    if (next && next.$$route && (next.$$route.originalPath === "/login" || next.$$route.originalPath === "/registration")){
                        event.preventDefault();
                        $location.path("/");
                    }
                }
            });
        });

    angular.module("controllers", []);
    angular.module("services", []);
    angular.module("directives", [])
})();

Why does the

$location.path(next.$$route.originalPath);
within the .success() AJAX call fail to work correctly? Note that replacing it with something like $location.path("/blah"); results in correct redirection, but even $location.path("/"); doesn't resolve the issue.

Answer №1

When using event.preventDefault() in Angular, it can cause the application to fallback to the root path if no current path is defined. This results in $location.path attempting to return to where you were, but ultimately not navigating anywhere.

Therefore, instead of using $location.path(), you should use $route.reload().

$http.get("http://localhost:8080/myapp/api/user?self=true")
                        .success(function (data) {
                            $rootScope.user = data;
                            if ($location.path() === next.$$route.originalPath) {
                                $route.reload();
                            } else {
                                $location.path(next.$$route.originalPath);
                            }
                        })
                        .error(function () {
                            $location.path("/login");
                        });

Answer №2

$timeout(function() {
    $window.location.href = '/new-path';
});

Everything should go smoothly. Remember:

event.stopImmediatePropagation();
works best with Angular 1.5+ and you must use $timeout instead of directly manipulating $window location.

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

Ways to keep selected values in the Select box without unchecking them again?

Hello there, I am relatively new to ReactJS and currently facing an issue with Selects. Specifically, I have a Select component that displays a list of names using MenuItem. My goal is to have certain names pre-selected in the Select dropdown upon initial ...

How to change the image source using jQuery when hovering over a div and set its class to active?

I am working with a div structure that looks like this: <div class="row margin-bottom-20"> <div class="col-md-3 service-box-v1" id="div1"> <div><a href="#"><img src="path" id="img1" /></a></div> ...

Retrieve the data from every dropdown menu

How can I retrieve the selected values from all created selects when a button is clicked? I have attempted using both refs and v-model, but neither of them are functioning as expected. <div v-for="attribute in attributes" class="col"> {{ a ...

I am currently transferring cross-site forgery tokens through jQuery strings. However, on the subsequent page, I create a fresh token which means their original tokens will no longer align

Alright, so I've been storing the tokens in a session: Session::get('token', 'randomtokenstringhere'); Every time a form is submitted, whether successfully or not, I generate a new token and update their session token. But let&ap ...

Discover the most frequent value in an array by utilizing JavaScript

My array contains repeating values: [0, 1, 6, 0, 1, 0] How can I efficiently determine the highest frequency of a specific value being repeated? For example, in this array, I would like the script to return 3 since the number 0 repeats most frequently a ...

Obtain asynchronous result from updating state in React

I am trying to achieve the following: myFunction = () => { this.setState( state => { const originalBar = state.bar; return { foo: "bar" }; }, () => ({ originalBar, newBar: state.foo }) //return this object ...

Using AngularJS ng-controller within an $http request is causing issues

I have an example of HTML code: <div ng-bind-html="model.main_container"></div> And I am executing something similar in AngularJS: $http.get("/submit", { cache: true }) .success(function(data, status) { if ( status == 200 ) { ...

The $resource.query function will now return an array of characters instead of a single string when splitting strings

Recently, I've been working on utilizing an Angular $resource in my project. Here's a snippet of the code: angular.module('app') .factory('data', function ($resource) { var Con = $resource('/api/data', {}, { ...

Inconsistency with Mobile Viewport Problem

Apologies for the chaos below, but I've spent quite some time attempting to fix this on my own. It's time to surrender and seek assistance! Here are some screenshots to illustrate the issue: The problem is that sometimes the webpage functions c ...

Parsing the JSON string from PHP using JSON.parse resulted in an unexpected and strange array

I've encountered a challenge when trying to transfer a JSON object from the server to client-side JavaScript. I fetched rows of data from a MySQL query and stored them in $result. Below is the code snippet: var json = '<?= json_encode($resu ...

The property of userNm is undefined and cannot be set

When attempting to retrieve a value from the database and store it in a variable, an error is encountered: core.js:6014 ERROR Error: Uncaught (in promise): TypeError: Cannot set property 'userNm' of undefined TypeError: Cannot set property &apos ...

Transferring a variable between a JavaScript function and a Java class

Currently, I am working with STS and building an application that includes HTML files and JavaScript. Within this file, there is a function that configures variables. <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www ...

Unable to access Vue component method beyond its scope

Having an issue with my Vue component that I'm trying to call a method from outside its wrapper element #app. Is there a way to register the component so I can easily call it like Component.function(); var viewController = new Vue({ el: "#app", ...

The promise object is displayed instead of the actual data retrieved from the API call

I am currently working on fetching data from an API and showcasing the name of the returned data on the front end. This function successfully retrieves the data through an API call: async function retrieveData(url){ var _data; let response = await fetch( ...

InvalidType Error: The roles provided are not in the correct format, it should be a Role, Snowflake, or an Array/Collection of Roles or Snowfl

Having trouble setting up multiple select menu options on Discord.js v14. I'd like to assign more than one role to a member when multiple options are chosen in the dropdown menu. However, I'm encountering this error message: TypeError [Invalid ...

The issue persists with the ajax.reload() function in DataTables

It's been driving me crazy that my datatables table won't refresh, despite using ajax.reload. I've spent weeks on this code but still can't get it to work. DataTablesDraw = (selector, order, pages, file, sort, column, template, data_se ...

Python Selenium error: NoSuchElementException - Unable to find the specified element

Coding Journey: With limited coding knowledge, I've attempted to learn through various resources without much success. Now, I'm taking a different approach by working on a project idea directly. The goal is to create a program that interacts wi ...

"Modifying the height of an SVG <g> element: A step-by

Is there a way to adjust the height of a g element? Trying to set the height using {params} but it's not responding I made some changes in the comments because the svg is quite large (Scene.js) {/* Transformation */} <g transform="trans ...

Is there a way to determine the dimensions of a pdf file using javascript and capture a snapshot of it for showcasing on a website?

I'm fairly new to HTML/CSS and haven't delved into javascript yet, but I have a good understanding of reading other people's code. Currently, I'm putting together my portfolio website and would like to include my resume on the page in a ...

Reducing Image Size in JavaScript Made Easy

I need help with a project where I want the image to shrink every time it's clicked until it disappears completely. I'm struggling to achieve this, can someone assist me? Here is the HTML code I have: <html lang="en" dir="l ...