observing the value of the parent controller from the UI router state's resolve function

I am facing an issue in my AngularJS application while using ui-router. There are three states set up - the parent state controller resolves a promise upon a successful request, and then executes the necessary code.

In the child state portfolio.modal.patent, I am using $stateProvider and the resolve method to make another request. The problem arises when I need the resolve method to wait until the promise returned in the parent controller portfolio is fulfilled.

States

$stateProvider
.state('portfolio', {
    url: '/portfolio',
    templateUrl: 'app/templates/portfolio/portfolio.tpl.htm',
    controller: 'portfolioCtrl',
    controllerAs: '$ctrl',
})
.state('portfolio.modal', {
    abstract: true,
    views: {
        "modal": {
            templateUrl: "app/templates/patent/modal.html"
        }
    }
})
.state('portfolio.modal.patent', {
    url: '/:patentId',
    resolve: { //NEED TO MAKE THIS RESOLVE AFTER PORTFOLIO CONTROLLER HAS RETURNED ITS PROMISE
        patent: ['$stateParams', 'patentsRestService', function($stateParams, patentsRestService) {
            return patentsRestService.fetchPatentItem($stateParams.patentId);

        }],
    }
}

Portfolio controller

function portfolioCtrl() {
    $scope.promise
    .then(function(response) {
          //WHEN PROMISIS RETURNED, THEN RESOLVE DATA IN PORTFOLIO.MODAL.PATENT
    })
}

Question

How can I ensure that the data for the child state portfolio.modal.patent is resolved only after the promise has been returned by the parent state controller portfolioCtrl

Answer №1

Find a quick workaround to address your issue by utilizing a service as a mediator for requests

For instance:

// create service
const bridge = $q.defer();
const resolveBridgePromise = data => bridge.resolve(data);
const getBridgePromise = () => bridge.promise;

// fetch data in parent controller
const fetchDataInParentCtrl = () => {
    $timeout(() => {
        console.log('Data fetched in parent controller');

        resolveBridgePromise({ key: 'fetched data' });
    }, 2000);
};

// call function to fetch data 
fetchDataInParentCtrl();

// retrieve data using resolver
getBridgePromise()
  .then(data => {
      console.log('Perform HTTP request here for child data: ', data);
  });

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

Unable to invoke the jQuery function within CakePHP3

I am having trouble calling the jQuery function mentioned below in my CakePHP3 MVC project. There are no error messages, but nothing seems to be happening. The code is set up so that jQuery gets included automatically. The function I am trying to call sh ...

Understanding the process of parsing an array in form-data in Node.js

https://i.stack.imgur.com/FPhX1.png I'm currently facing an issue while trying to read the image above in Node.js. I am using Express.js and have attempted to debug req.body, but it is returning an empty object {}. Even though I am using app.use(bod ...

Tips for inserting a component into a div selector using Angular 2

Could someone please help me figure out how to inject a component into a div selector using a class or id? I'm familiar with injecting components into other components, but not sure how to do it specifically within a div. Any guidance would be greatly ...

"Fill the designated area on the webpage with data retrieved from an external script

In my current project, I am utilizing Angular and JQuery to enhance re-usability by setting the header and footer as partials. However, I encountered an issue where I needed certain javascript functions to be executed within the footer upon loading - a tas ...

Import and load numerous JSON files into a responsive and visually appealing Bootstrap table

I am new to coding in javascript and I'm seeking assistance in loading multiple JSON files to populate a bootstrap table. Currently, I've managed to create a table by manually combining the content from different files into one variable called l ...

Continuous front-end promise awaiting response from back-end Node.js function

Currently, I am working on a basic React frontend where I need to fetch some data from my backend API powered by Node.js. This backend API calls an external API to get the required data. Although I have verified that the data is fetched successfully on the ...

Is there a shared code base in Angular for multiple ng-switch cases?

Is there a way to replicate the behavior of this switch statement using Angular's ng-switch directive? switch(variable){ case 'sample1': case 'sample2': //Common functionality for both 'sample1' and 'sample2&apos ...

What is causing the "unable to resolve dependency tree" error when using ng new newApp?

Struggling with creating a new Angular app using the command ng new app-name? When running the command, you may encounter the following error in the command line. Installing packages (npm)...npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve depen ...

The width of an HTML input and button elements do not match

Currently, I am facing an unusual issue where my input and button tags seem to have the same width assigned to them (width: 341.5px; calculated from $(window).width() / 4) in the code, but visually they appear to be of different widths. Here is a visual re ...

Transmit information from an HTML input field (not a form) to a Python CGI script through AJAX

I am currently facing a challenge where I need to send data programmatically without using form fields directly to a python CGI script. The issue lies in not knowing how to extract this data in Python. Normally, with a form, I could use "form = cgi.FieldSt ...

Can PHP send back data to AJAX using variables, possibly in an array format?

My goal is to transmit a datastring via AJAX to a PHP page, receive variables back, and have jQuery populate different elements with those variables. I envision being able to achieve this by simply writing: $('.elemA').html($variableA); $('. ...

Triggering a gTag Event on the Fly using Google Tag Manager

I implemented a script that triggers a dynamic gTag.js AdWords conversion based on various user interactions on my webpage. Everything was working smoothly until I switched to Google Tag Manager. Now, the code snippet: gtag('event', 'convers ...

PHP response triggers AJAX autocomplete functionality in JavaScript

The autocomplete hints are not displaying any response for me. Here is the jQuery code that I am using: jQuery( ".newtag_new" ).autocomplete({ minLength: 0, source: function( request, response ) { jQuery.ajax({ type: 'GET ...

Exploring the intricacies of Bower and enhancing dependency management

Currently, I am working on developing a project named myapp using angularJS along with Yeoman Generator. This project involves utilizing Bower to manage dependencies and Grunt to wiredep those dependencies into the index.html file (which essentially genera ...

"Is there a way to retrieve the CSS of all elements on a webpage by providing a URL using

Currently, I am in the process of creating a script that can crawl through all links provided with a site's URL and verify if the font used on each page is helvetica. Below is the code snippet I have put together (partially obtained online). var requ ...

Angular.js: Utilizing ng-repeat to iterate through items within an object

There are two ng-repeats on the page that share an Object. The items should only be repeated if they match the type data. Sample Object $scope.events = [ { date: "1/16/13", time: "11:30", ...

Having trouble connecting to the webserver? Make sure the web server is up and running, and that incoming HTTP requests are not being blocked by a firewall

While working on my Visual Studio 2013 Asp.Net web code using the Local IIS Web server Version 7 (Windows 7 x64) and Framework 4.0, I encountered an error message stating: "Unable to start debugging on the web server. Unable to connect to the webserver. V ...

What is the process for integrating ion-tabs with IonicVueRouter within an Ionic (vue.js) application?

My Project Idea I have a vision to create an innovative exercise warm-up application. The app will be divided into two main sections: a workout tab and a settings tab. The user journey will start with selecting a workout plan, then choosing specific exerc ...

Adjust the HTML 5 range slider to update according to the selected value

Is it possible to create a custom marker on an HTML5 range input element? I'm looking for a way to change the design of the circle marker as it moves along the scale from 1 to 10. Specifically, I want to change the color of the marker based on its po ...

Storing the value from the INPUT field in the state of React is not permitted

I'm attempting to retrieve the user input value from the INPUT field and update it in the corresponding state. However, no matter what I type in the field, it doesn't get set to the state. createForm(x){ var dx = 'd'+x let da ...