Leveraging $http and $q in an Angular configuration with a service/provider

My goal is to load specific configurations for each controller in the app.config section. Each controller requires a distinct set of data, but these sets are not mutually exclusive. I am struggling to find a solution to this issue.

.config(['$routeProvider', '$locationProvider', 
        function($routeProvider, $locationProvider){


    $routeProvider
    .when('/', {
        templateUrl: "partials/pages/dashboard.html",
        controller: "dashboard_controller",
        resolve: { dash_config: 'SomeConfigD'},
    })
    .when('/a', {
        templateUrl: "partials/pages/a.html",
        controller: "a_controller",
        resolve: { dash_config: 'SomeConfigA'},
    })
}])

However, I don't want to create separate factories for someConfigA and someConfigD, as they have shared code. What I need is something like the following:

app.factory('configFactory', function(...){
    var factory = ;

    function get1(){
        // make some $http calls here and return a promise
    }

    function get2(){
        // make some $http calls here and return a promise
    }

    function get3(){
        // make some $http calls here and return a promise
    }
    factory.configA = function(){
        // return a promise to resolve both get1 and get2
    };
    factory.configD = function(){
        // return a promise to resolve both get2 and get3
    };
})

Is there a way to accomplish this?

Answer №1

It appears that the solution you are seeking is $q.all, which can be found by visiting this link.

I have also created a JSFiddle utilizing your factory. I integrated it into the run method of the module to avoid dealing with factory creation. The code snippet looks like this:

f.configA = function(){
    var get12 = $q.all([
        get1().then(thenFn),
        get2().then(thenFn)
    ]).then(function() {
        console.log('both resolved');
    });
    return get12;
};

The function within the 'then' block will only execute once both promises have been resolved, even if they happen at different times (simulated using $timeout)

You now have reusable get functions. I hope this explanation proves helpful!

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

How to implement a cyclic item generation feature in React.js

My function is meant to draw multiple items in a cycle, but it is only drawing the first item when I attempt to draw 5. This is my function: export default function CinemaHole() { const items = []; for(let i = 0; i < 5; i++) { item ...

Incorporate PrimeVue into Vue's custom elements

Can you guide me on integrating a PrimeVue component into a Vue3 custom element? I have created a Vue3 composition+setup custom element. I expect the button to be styled with PrimeVue and appear red due to the severity="danger" attribute. Howev ...

Ways to substitute numerous instances of a string in javascript

I have experience in developing websites using reactjs. I usually implement restAPI's with java and work with liferay CMS. In one of my projects, I created a shortcode for accordion functionality like this: ('[accordion][acc-header]Heading 1[/ac ...

Problem with Bootstrap 3 navbar on mobile devices - not tappable or responsive

After years of using Bootstrap, I've come across a new issue with my implementation of a Bootstrap 3 Nav. While testing on a desktop browser with device emulation, the nav collapses and functions properly. However, when tapping on the header on an ac ...

Diminishing sheets in the realm of C# web application development

I have been researching ways to incorporate a fading page function, but I am encountering some issues. I am unsure about the specific code that needs to be included in jquery.js and how to integrate this script into all of my web forms or alternatively int ...

The error message "Type Error: val.toString is not a function - mysql npm" indicates

I'm encountering an issue with the 'mysql' package in NPM on a nodeJS backend and I'm puzzled by this error message: TypeError: val.toString is not a function at Object.escape (/Applications/MAMP/htdocs/nodeJS_livredor/node_modules/sql ...

The useState hook is failing to properly initialize with the provided props value

I am facing an issue with two components in my code. In the App component, I initialize a variable called chosenCount with zero and then set it to a different value (e.g., 56). However, when I click the set button, the Counter component is supposed to rece ...

Tips for extracting an XML value from an API

I'm attempting to showcase a value retrieved from an API (specifically used by PRTG software to extract information). Here is the link to the API: The API provides an XML file structured like this: <?xml version="1.0" encoding="UTF-8"?> <ch ...

Merge Razor with Ajax and JSON

I have been struggling to get the following components to work together without success. The goal is to populate the mediaId's combobox with respective values based on the selection in the target combobox. Currently, I am only simulating the values fo ...

Is there a method to determine whether the user has granted permission for notifications to be enabled?

Once I have requested permission from the user of the website, I need to confirm if they have granted permission before triggering the send() function. What is the most sophisticated approach to achieve this? ...

How can I launch five separate instances of Chrome on a Selenium grid, each with a different URL?

I have a list of URLs saved in a JSON file, structured like this: { "urls": [ "http://www.google.com/", "http://www.stackoverflow.com" ] } Currently, these URLs are being opened sequentially by the Selenium WebDriver JavaScript manager on a ...

default choice in dropdown menus

I need to populate my option fields with data retrieved from a database. I encountered an error in the console: Error: [$compile:ctreq] Controller 'select', required by directive 'ngOptions', can't be found! I am confident that t ...

Guide on embedding a form component within an iframe using ReactJS

I am trying to figure out how to render my form component inside an iframe, but so far it's only rendering the iframe itself. Any tips on how to accomplish this task? import './App.css'; import ReactDOM from "react-dom/client" impo ...

Encountered issues while installing a package with npm instead of yarn

I have established a Git repository that will serve as an NPM package in another project. Let's refer to this sharable repository as genesis-service-broker. Within one of my services (specifically the activation service), I am utilizing this shareabl ...

Issue with Angular 12 service worker causing SW update to fail

I'm currently working on integrating a service worker into my Angular application to enable updates without user intervention. Here is the step-by-step process that I am following: Make changes to the application Run ng build Start an HTTP ser ...

The link does not respond to the first click

I'm having an issue with the search feature on my website. The page includes an auto-focused text input element. As the user types, an ajax request is made and JQuery fills a div with search results. Each result is represented by an <li> elemen ...

Limit DerbyJS to re-rendering specific DOM elements

Currently, DerbyJS (visit http://derbyjs.com) functions by replacing everything in the body tag of the document each time a link is clicked. Is there a way to utilize the template, but replace only the content inside #main-content instead of refreshing th ...

A guide on integrating a Google Maps API_KEY with angular-google-maps 2.2.1

In the midst of my current mobile app project, I am dealing with an application that was created back in 2016 and currently has around 4500 users. The app was built using AngularJS (v 1.7.8) and IONIC (V1.1.1), and we are required to stick with these older ...

Have you checked the console.log messages?

As a newcomer to web development, I hope you can forgive me if my question sounds a bit naive. I'm curious to know whether it's feasible to capture a value from the browser console and use it as a variable in JavaScript. For instance, when I enco ...

When attempting to incorporate Jasmine into my current AngularJS/Bootstrap project, I encountered the error message stating

Currently, I am working on a group project that requires test coverage. The project utilizes npm and angularJS. To kick things off, I performed an npm install for jquery, jasmine, and angular-mocks. Since I'm relatively new to testing, I decided to st ...