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

Tips for utilizing ajax function to refresh database entries

I am working with a customer information table that is populated from a database. The last column in this table contains an edit button which, when clicked, shows a popup window with text fields pre-filled with database values. I want users to be able to u ...

Attempting to eliminate redundant data retrieved from an XML file being presented on my webpage

I need help deleting duplicate artists that appear when retrieving information from an XML file using JQuery. How can I achieve this? Check out the JS file below: $(function(){ $(window).load(function(){ $.ajax({ url: 'http://imagination ...

What is the best way to integrate a loop in JavaScript to retrieve values?

<script> var data={ Data: { name: 'aaaa', number: '0003' }, values: { val: '-20.00', rate: '22047' }, user: [ '6|1|5', '10|1|15' ] }; ...

Tips on changing the color of a dropdown select option in Angular 8

I have been experimenting with changing the color of a dropdown select menu based on the value selected by the user. Here is the code I have been working with: App.component.ts @Component({ selector: 'my-app', templateUrl: './app.comp ...

"Materialize and AngularJS: A dynamic duo for web

Currently, I am utilizing Materialize CSS for the design of my website and incorporating AngularJS to enhance its flexibility. However, I have encountered some issues with certain properties of Materialize (such as Select, date-picker, radio-button) not wo ...

Displaying outcomes in dialog box when button is pressed

I am working on a website where I want to enhance the user experience by displaying output in a dialogue box upon click. The current setup involves the user selecting a vendor and time duration, with the results appearing below the Submit button. However, ...

Generating a container DIV with loops and ng-class in AngularJS

Currently, I am working on developing a dynamic timeline using AngularJS. To populate my timeline, I have successfully configured the data fetching from a JSON file. You can see what I have accomplished so far on PLNKR: http://plnkr.co/edit/avRkVJNJMs4Ig5m ...

When using angular $resource.save for savings, the view is forced to redraw and reflow because of the collection watcher

One of the challenges I'm facing involves loading and storing a model using $resource in AngularJS. This particular model is an aggregate with nested collections, which are displayed in an HTML view using ng-repeat. The structure of the model looks l ...

When triggered by a click, the function gradually fades in and out. It superimposes one image on top of another, but unfortunately, the sizes

Due to different screen sizes, the image does not appear on top of another image exactly. It seems like a new function is needed. One that does not overlap with another image (by clicking the function for a few seconds), but rather replaces it for those fe ...

"Enhancing security with Spring, managing admin roles through a gateway, and

Currently, I have implemented gateway-based authentication within Spring Security. The user's credentials are authenticated against the database. After successful authentication, the user is routed to the UI microservice through Zuul. However, when an ...

Issue with AngularJs failing to display data

As a newcomer to AngularJS, I am looking to utilize AngularJs to display the Json output from my MVC controller. Here is the code snippet for my MVC Controller that generates Json: [HttpGet] public JsonResult GetAllData() { ...

Determine the Size of an Image File on Internet Explorer

Is there an alternative method? How can I retrieve file size without relying on ActiveX in JavaScript? I have implemented an image uploading feature with a maximum limit of 1 GB in my script. To determine the size of the uploaded image file using Java ...

The ng-repeat function in AngularJs does not display the data despite receiving a successful 200 response

As part of my academic assignment, I am exploring Angularjs for the first time to display data on a webpage. Despite receiving a successful http response code 200 in the Chrome console indicating that the data is retrieved, I am facing issues with displayi ...

if statement for a method within the ng-click directive

Whenever I click the button, I want to either execute createRole() if RoleName is not set or EditRole() method if RoleName is set. However, for some reason, EditRole() is being executed for both cases. <button type="submit" ng-click="selectedItem.Rol ...

Achieve top-notch performance with an integrated iFrame feature in Angular

I am trying to find a method to determine if my iframe is causing a bottleneck and switch to a different source if necessary. Is it possible to achieve this using the Performance API? This is what I currently have in my (Angular) Frontend: <app-player ...

The most effective method for transforming an array into an object in JavaScript using a prefixed value as the key

I am working with an array that contains prefix values ["options_a", "options_b", "options_c", "capable_d", "capable_e_c" ] I am looking for a way to transform this array into an object format with the pre ...

Creating an error message display function using HTML and JavaScript when incorrect input is detected

I am having trouble creating an HTML5 and JS program that will show an error message if the user input is empty. Despite my efforts, I can't seem to get the "Error Message" to display. As a beginner, the video tutorial I'm following doesn't ...

Preventing file visibility in Three.js resource directory

Once a user clicks on a specific 3D model, I retrieve it from the server and render it in the browser using three.js. However, there is an issue when the user tries to access a model that is not free - they can easily view and download the STL file by go ...

What is the method for obtaining the entire object as a response following a click?

I am working on a basic JavaScript snippet: var image = [{name: "Breakfast", age: 100, author: "Alice"},{name: "Dinner", age: 10, author: "Teddy"}]; function gallery(name, content) { this.name = name; this.c ...

Click on an image to dismiss a material-ui dialog

Trying to include a clickable image to close a material-ui dialog, but encountering an issue where the onClick event is not responding. The props.onRequestClose function works fine when clicking outside of the dialog. What could be causing this problem? ...