Waiting for a promise in Angular's ui-router before navigating to a new route

My current setup involves Angular 1.5.8 and angular-ui-router 0.3.2. Every time a route changes, I need to authenticate the user.

To avoid adding the resolve property for each route individually, I decided to handle this in App.run

//check permissions

$rootScope.$on('$stateChangeStart', function (evt, toState) {
    if ($localStorage.token || toState.authenticated) {
        $http.defaults.headers.common = {
            'Authorization': 'Token ' + $localStorage.token,
            'Accept': 'application/json'
        };

        permissionAPI.me()
            .then(function(data){
                $rootScope.user = data;
            })
            .catch(function(){
                if(toState.authenticated) {
                    $rootScope.logout();
                }
            })
    }
    else {
        if(toState.authenticated) {
            $rootScope.logout();
        }
    }
});

`

While this approach generally works fine, there are instances where the application routes before the promise permissionAPI.me() is resolved, leading to errors later on.

How can I ensure that the route only takes effect after the promise has been fulfilled?

Alternatively, is there a way to set up a single main resolve for all routes by passing the promise from $stateChangeStart?

Thank you!

Answer №1

Develop a foundational app state! Utilizing abstract states can be beneficial when you require consistent data accessibility throughout your application, without tying that data to a specific view.

    $stateProvider
        .state('app', { 
            url: '/app/',
            template: '<div ui-view></div>',
            controller: 'AppCtrl',
            abstract: true,
            resolve: {
                ActiveUser: function (AuthService) {
                    return AuthService.whoAmI();
                }
            }
        })
        .state('app.home', {
            url: '',
            templateUrl: 'app.home.html',
            controller: 'HomeCtrl',
            resolve: {
                Categories: function (ActiveUser, MessagesService) {
                    return MessagesService.getAll(User);
                }
            }
        });

You can then utilize this data in subsequent resolve blocks or within your controllers using

app.controller('ExampleCtrl', function (ActiveUser) {});
as long as the controller is nested under the parent state of 'app'. This structure is established by the naming convention 'app.'

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 stopping ajax requests from automatically following redirects in jQuery

When utilizing the jQuery ajax functions to connect with a web service, I encounter an issue where the server redirects the response to a page with a 200 status code instead of providing a proper status code indicating an error. Unfortunately, I am unable ...

Is there a way for me to obtain the present value of the chosen button in the list below?

I am working with a group of three buttons labeled English, Hindi, and Urdu. How can I retrieve the value of the selected button in a JavaScript function? <div class="btn-group" data-toggle="buttons"> <label class="btn btn-primary active"> ...

What is the best way to transform a collection of items into FormData?

In my current project, I have a JavaScript array structured as follows: var items = [{ ID: "1" count:'1', File: (binary file) }, { ID: "2" count:'2', File: (binary file) } ] My goal is to ...

Rendering on the server using react-router v4 and express.js

I've been working on implementing server-side rendering with the latest version of react-router v.4. I found a tutorial that I followed at this link: . However, when I refresh the browser, I encounter the following error: Invariant Violation: React.C ...

A guide to sorting an object with integer keys by its values using JavaScript

I am facing an issue with sorting a map by values instead of keys. No matter what I do, it always ends up getting sorted by the keys. On the server side, I have a map that is already sorted. When I send this map to JavaScript using JSON, it gets re-ordere ...

Can we send a dynamic form using AJAX?

I am seeking a method to submit a page filled with quantities to another page and then retrieve their values. Here is my setup: <input type="number" name="item1" /> <input type="number" name="item2" /> <input type="number" name="item3" /> ...

Utilize the Twitter Bootstrap modal feature to play autoplaying Youtube videos that automatically pause when

Similar Question: How do I halt a video using Javascript on Youtube? I am curious about how I can utilize the modal feature in Twitter Bootstrap to automatically play a Youtube video, and when a user clicks the "close" button, it will cease the video ...

An issue arose when attempting to proxy to: localhost, at port 4200, for the API endpoint v1/generate

Currently, I am following a tutorial which guides me through the process of creating an application using Angular CLI, Node.js, and Express. A proxy is used to initiate the app, with the proxy configuration file looking like this: { "/api/*": { ...

The most efficient way to invoke a jws void method in the fewest steps possible

When calling a void method of a SOAP JWS web-service using JavaScript without expecting a result back, what is the most efficient and concise approach? ...

What significance does #! hold in the context of ui.router?

I am utilizing the Angular ui.router in navigating throughout my application. Typically, the URL should appear like this: http://localhost:8001/#/start However, in my scenario, it appears like this: http://localhost:8001/#!/start What is the significan ...

Can JavaScript executed within a web browser have the capability to manipulate files on the underlying host system's file system?

Is it possible to programmatically move files or folders from a website using code? I am aware that with Python and Node.js, this can be achieved through the OS, path, and fs modules. Can JavaScript running in a website also handle file management tasks ...

Store and Persist Data for a Model in MongoDB

Currently working through the MongoDB and Mongoose section on FreeCodeCamp. The challenge involves creating a document instance using the Person constructor previously built. The object passed to the constructor should have fields for name, age, and favor ...

Is it possible to selectively render a page or component in Next.js 13 based on the request method?

Is there a way to conditionally render a page based on the request method in Nextjs 13? For example, when registering a user, can we show a signup form on a get request and display results on a post request? With all components now being server components ...

Complete a checkbox entry form and showcase it within a "division" on the current page

Hello everyone, I need some help. I have a form that I want to send to a specific div on the same page. This is what I am aiming for. I have a floating div named "basket" in the top right corner of my page where I want the form data to be displayed after s ...

Implement a Vue binding that applies an active class on click, replacing the previous one

I have a loop that dynamically adds div sections to the page. I want the first one to be selected on page load, and then when another one is clicked, it should become active while the previous one loses its active status. I attempted the code below but it ...

Encountering the error message "Unable to access property 'addEventListener' of null while trying to manipulate innerHTML"

Currently, I am utilizing innerHTML to include certain elements and a wrapper around them. for (i = 0; i < arr.length; i++) { b.innerHTML += "<div class='wrapper'><div class='col-4'>" + arr[i].storeID + "</div> ...

How can I add divs to an HTML page with a Javascript animated background?

I am currently facing an issue with my JavaScript animated background, consisting of just 3 pictures. I am trying to display some Div elements on it with content inside. Here is the code snippet I have right now: In my CSS file, I have defined styles for ...

How can changes be spread to other stores within the react flux flow?

My project has a simple structure consisting of 1 store, 2 components (parent and child, with the parent acting as a controller), actions, and constants. Currently, I am not making any API calls; all data is passed to the parent component as props. The fl ...

Tips on sorting JSON data with Angular

Trying to categorize JSON Data into online and offline users with errors. The criteria are based on the presence of a 'stream' object (online), absence of a 'stream' object (offline), and the presence of an 'error' property. ...

Using Regular Expression to verify the presence of numbers and spaces

Currently, I have implemented a regular expression that ensures my string contains 5 digits. While this regex works flawlessly, I now also require it to allow white spaces: both "123 45" and "12345" should meet the criteria. string.match(/^\d{5}$/g); ...