Exploring the flow of resolve promises in UI-router from the main root state to its sub-states

Currently, I am in the process of developing an Angular application with ui-router.

The first step I took was to create a root state that serves as an abstract one intended for resolving asynchronous dependencies. This means that any subsequent sub-states should be able to utilize these dependencies in their own resolve state properties. Therefore, if the abstract root state is resolving async dependencies and a sub-state also needs to resolve async dependencies, the latter should wait for the root dependencies to be resolved before initiating its own resolve method. Isn't this correct?

Below is a code example that illustrates my point:

Here are the asynchronous, promise-based methods utilized within the corresponding resolve:

 public iAmInTheRootState(): IPromise<any> {
    let deferred = this._$q.defer();

    this._$timeout(() => {
        deferred.resolve();
    }, 3000);

    return <IPromise<any>> deferred.promise;
}

public iAmInTheSubState(): IPromise<any> {
    let deferred = this._$q.defer();

    this._$timeout(() => {
        deferred.resolve();
    }, 100);

    return <IPromise<any>> deferred.promise;
}

Abstract Root State:

$stateProvider
    .state('app', {
        url: '/',
        abstract: true,
        templateUrl: 'layout/app-view.html',
        resolve: {
            auth: function (Auth: IAuthService) {
                'ngInject';
                return Auth.iAmInTheRootState().then(() => {
                    console.log('I am the root state, so I should be resolved first');
                });
            }
        }
    });

Sub-State (Daughter State):

$stateProvider.state('app.my-calls', {
    url: '',
    controller: 'MyCallsController',
    controllerAs: '$ctrl',
    templateUrl: 'states/my-calls/my-calls.html',
    resolve: {
        secondAuth: (Auth: IAuthService) => {
            'ngInject';
            return Auth.iAmInTheSubState().then( () => {
                console.log('Even though I am quicker, I should be resolved second because I am in the sub-state');
            });
        }
    }
})

However, the actual output differs from what I had anticipated:

https://i.stack.imgur.com/Y1lAS.png

Answer №1

It is important to note that in the given scenario, the 'app.my-calls' state is actually created after the 'app' state (this can be confirmed by logging the onEnter callback).

Refer to Ui-router wiki for more information.

Utilizing Resolve Functionality

The resolve feature allows you to furnish your controller with unique content or data specific to the state. It serves as an optional dependency map that gets injected into the controller.

If any of these dependencies happen to be promises, they will be resolved and transformed into a value before the controller instantiation takes place and the $stateChangeSuccess event occurs.

It is essential to understand that the resolve callback does not serve to postpone the creation of the state, but rather it delays the instantiation of the controller itself.

To gain a comprehensive understanding of the entire process flow, consider logging both the $stateChangeStart and $stateChangeSuccess events.

Answer №2

While Tim's response directly addresses my query, it may be beneficial to explore how sub states can wait for their parent's resolve method.

To delve deeper into this discussion, refer to the GitHub issue related to this subject.

In essence: sub states should have the parent state as a prerequisite:

Parent State:

$stateProvider
.state('app', {
    url: '/',
    abstract: true,
    templateUrl: 'layout/app-view.html',
    resolve: {
        ParentAuth: function (Auth: IAuthService) {
            'ngInject';
            return Auth.iAmInTheRootState().then(() => {
                console.log('I am in the root state and should take precedence.');
            });
        }
    }
});

Child state:

$stateProvider.state('app.my-calls', {
url: '',
controller: 'MyCallsController',
controllerAs: '$ctrl',
templateUrl: 'states/my-calls/my-calls.html',
resolve: {
    SubAuth: (ParentAuth, Auth: IAuthService) => {
        'ngInject';
        return Auth.iAmInTheSubState().then( () => {
            console.log('Even though I'm faster, I should come second because I'm in the sub state.');
        });
    }
 }
 })

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

Inject nested controller dynamically

I am working on a straightforward ASP.NET MVC application that includes an ng-controller. I am trying to inject another ng-controller inside this controller using a partial view, but I'm having trouble getting the binding to work correctly. You can s ...

Error: global not declared in the context of web3

I've been attempting to integrate Web3 into my Ionic v4 project for some time now. However, I keep encountering errors when I try to serve the project. Specifically, I receive an error message stating that Reference Error: global is not defined. Cre ...

Converting hexadecimal to binary using Javascript or Typescript before writing a file on an Android or iOS device

Hey everyone! I'm facing a puzzling issue and I can't seem to figure out why it's happening. I need to download a file that is stored in hex format, so I have to first read it as hex, convert it to binary, and then write it onto an Android/ ...

Angular-material's Md-dialog popup box is displayed as a separate view within the Yeoman framework

I have recently created a project using Yeoman (angular-fullstack, angular-material) and encountered an issue with triggering the md-dialog box. When clicking on a div element, the dialog box is supposed to appear. However, instead of showing the popup the ...

What is the best way to set up a server in React using Express or HTTP?

I am currently in the process of developing a web application using react js. In order to create a server for my client within the project, I have decided to utilize either express or http. Here is the code snippet that I attempted: import React from " ...

Issue: In an Angular electron app, a ReferenceError is thrown indicating that 'cv' is

I have been working on a face detection app using OpenCv.js within an Angular electron application. To implement this, I decided to utilize the ng-open-cv module from npm modules. However, when attempting to inject the NgOpenCVService into the constructor ...

A custom class that uses toggleClass() does not trigger an alert upon a click event

I am encountering an issue with the toggleClass() function in jQuery that I haven't seen addressed before. Despite successfully toggling the class of one button when clicked, I am unable to trigger a click event on the newly toggled class. Here is th ...

Is it possible for Node.js to not automatically restart the server when modifying .js files?

Right now I have node-supervisor set up to detect changes in .js files, and while it works well, I've realized that it restarts the server every time a js file is saved. Is there a way to save a server-side .js file without triggering a server restart ...

Unable to refresh JSON data in Datatables

Ensuring this operation is simple, I am following the documentation. An ajax call returns a dataset in JSON format. The table is cleared successfully, but even though data is returned according to the console statement, the table remains empty after the su ...

Instead of showing the data in the variable "ionic", there is a display of "[object object]"

Here is the code snippet I'm working with: this.facebook.login(['email', 'public_profile']).then((response: FacebookLoginResponse) => { this.facebook.api('me?fields=id,name,email,first_name,picture.width(720).height( ...

Having difficulty installing the yarn package from GitHub

I'm attempting to install a GitHub package using yarn. I've tried this process many times before, but I have not been successful with this particular repository: https://github.com/coolwanglu/pdf2htmlEX I have already attempted the following w ...

Passing a Value from Child to Parent Function in Meteor: A Complete Guide

I am trying to pass the value of a result from a child element to its parent element. Initially, I used Session.set and Session.get which worked fine but I realize that using Sessions globally is not considered good practice. So, I attempted to utilize rea ...

Tips for toggling ng-class in AngularJS

My current challenge is toggling classes with ng-class, especially when dealing with tabs that contain sub <a>. Here is the relevant HTML code: <ul class="nav navbar-nav navbar-right"> <li ng-class="{active:isActive('/home')}" ...

Converting milliseconds into days, hours, minutes, and seconds using Angular

Currently, I am attempting to convert milliseconds to the format dd:hh:mm:ss. For example, given 206000 milliseconds. The desired format for this value would be: 00:00:03:26. However, when utilizing the following code: showTimeWithHour(milliSeconds: numb ...

Having trouble with the $.post method not loading my PHP file in my

I followed a tutorial on YouTube to copy the code, adjusted the database connection and SELECT items to fit my existing DB, but I'm struggling to get the JS file to load the PHP file. When I use Chrome's "inspect" tool, it shows that the JS file ...

Unable to display information from a repeated `textarea` in ngRepeat

Check out my code on Plunker: https://plnkr.co/edit/rBGQyOpi9lS0QtnCUq4L I'm trying to log the content of each textarea when typing, using the printStuff() function: $scope.printStuff = function(customize, item) { console.log(customize[item.inde ...

Establishing a connection with Taffy DB using Node.js

Currently, I am in the process of developing an application that utilizes Angular js, Node js, and Taffy DB. The main challenge I am facing involves storing the data submitted from the front-end into Taffy DB through the Node js server. var express = req ...

Why isn't changing the property of a Sequelize instance having any effect?

While I've successfully used the standard instance syntax in the past, I'm facing a challenge with updating an instance retrieved from the database in this specific section of my code. ... const userInstance = await db.models.Users.findOne({wher ...

Guide on converting HTML datetime picker datetime-local to moment format

I am looking to convert an input type : <input type="datetime-local" name="sdTime" id="stTimeID" onChange={this.stDateTime} /> into a specific date format: const dateFormat = 'MM/DD/YYYY hh:mm:ss a'; To achieve this, I need to transfer ...

"415 (Unsupported Media Type) encountered when making a POST request in a REST API

I've encountered an issue with a React component where a checkbox triggers a POST request to a REST API with a single parameter. Despite setting a breakpoint in the WebAPI code, it's not being hit and I'm receiving a 415 Unsupported Media Ty ...