Is sending an HTTP request in Angular's configuration an achievable task?

My goal is to dynamically retrieve an array of available routes to match with the $urlMatcherFactoryProvider by making an $http call inside my publicApp.config.

Currently, I have hard-coded the routes as

pageUrls = ['about','contact','another-page'];

However, there is an API endpoint in my express server that returns the list of available URLs. The API URL is "/page-urls"

I am wondering if it is possible to issue an $http.get('/page-urls') request within the configuration phase. While I know that $http can be used inside the run() function, I need the list of URLs before setting up routing via the $stateProvider.

(function() {
    'use strict'

    var pageUrls = [];

    var publicApp = angular.module('publicApp', ['ui.router'])

    publicApp.config(['$stateProvider', '$urlRouterProvider', '$urlMatcherFactoryProvider', function($stateProvider, $urlRouterProvider, $urlMatcherFactoryProvider) {

        pageUrls = ['about','contact','another-page'];  

        var urls = pageUrls.join('|');
        var urlMatcher = $urlMatcherFactoryProvider.compile("/{source:(?:" + urls + ")}");

        $stateProvider      
            .state('/', {
                url: '/',
                templateUrl: "views/home/home.view.html",
                controller: "homeCtrl"
            })
            .state('urls', {
                    url: urlMatcher,
                    templateUrl: "views/pages/page.view.html",
                    controller: "pageCtrl"
                });

            $urlRouterProvider.otherwise('/');

    }]);

})();

Answer №1

Develop a custom provider that requires the $stateProvider as an injectable parameter. This provider will be responsible for creating a service that makes HTTP requests and then sets up the routes accordingly. The service should be injected into a run block to start the route registration process.

You can implement it like this:


var publicApp = angular.module('publicApp', ['ui.router'])

publicApp.provider('routes', function($stateProvider, $urlRouterProvider, $urlMatcherFactoryProvider){
    function registerRoutes(listOfUrls){
        // Logic to register routes using $stateProvider
        // angular.forEach(listOfUrls, function(url){
        //     $stateProvider.state...
        // });
    }

    this.$get = function($http){
        return {
            initialize: function(){
                return $http.get('/page-urls').then(function(response){
                    registerRoutes(response.data);
                });
            }
        };
    };
});

publicApp.run(function(routes){
    routes.initialize();
});

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

Steps to invoke another service (function) prior to calling the res.view() function in sails JS:

I am looking to execute a separate function, like a Service function, before Sails renders the page into HTML. Please refer to the controller code below... var MYController = { index: function(req, res, next) { req.flash("error", "Testing hello ...

Creating default selection in angular 6 using formControlName in a dropdown menu

I am currently learning MEAN stack with Angular 6 and I have a question regarding selecting the default value in a dropdown using formControlName. When updating a form, I need to have a default value in my dropdown list but I'm only getting a blank op ...

Google's questionable actions during the user verification process using nodejs raised concerns

In my Nodejs project, I've implemented a user authentication system that involves sending confirmation emails for account verification. Once a user creates an account, they receive an email with a URL to click on and verify their account - a process ...

Building Pagination Feature in Node.JS and Express using SWAPI and Axios

After numerous attempts, I managed to retrieve data from SWAPI but only the first 10 people were being displayed. Seeking a solution, I found that utilizing async functions was the key. const express = require("express"); const router = express.R ...

Inform the client of a "404 Not Found" Error when using the PUT method

Whenever I click the Submit button, I encounter a 404 Not Found Error when trying to call the "publish-template" endpoint. Why does this error occur even though it supposedly exists? The Pug rendering is done with the correct path for the form action: doc ...

How can I omit extra fields when using express-validator?

Currently, I am integrating express-validator into my express application and facing an issue with preventing extra fields from being included in POST requests. The main reason for this restriction is that I pass the value of req.body to my ORM for databas ...

AngularJS $scope variable can be initialized only once using an HTTP GET request

I'm facing an issue with fetching data from an API in a separate AngularJS application. There's a button that triggers the retrieval of data from the API. Upon clicking, it executes the $scope.getApiData function, which is connected to $scope.pr ...

Does Model.find() in MongoDB return an object or an array of objects?

const trips = await Trip.find() After using console.log(typeof trips), it displayed 'object' in the console log. However, when I used console.log(trips), it showed an array of objects. This has left me slightly puzzled about what is actually bei ...

Step-by-step guide on how to prioritize rendering the login page before the ngView in AngularJS in order to

As I begin my journey with Angular JS, I am eager to implement security measures in my application. My intention is to set up a log-in page as the default landing page for my single page application. Can anyone provide guidance or recommendations on how ...

What sets AngularJS service, provider, and factory apart?

I'm feeling a bit confused about the service, provider, and factory in AngularJS modules. Can you please explain the differences between these three components and provide examples for better understanding? ...

Exploring the Potential of Express and Mongoose through Mocha Testing

I'm currently experimenting with testing my REST API endpoint handlers using Mocha and Chai. The application was developed using Express and Mongoose. Most of my handlers follow this structure: var handler = function (req, res, next) { // Process ...

Using AngularJS ng-options with templates embedded within

I am trying to enhance a dropdown select by adding text and an icon to it. This is my starting point: <select ng-change="actions.change()" ng-model="variant_id" ng-options='variant.id as variant.name for variant in variants'&g ...

Prevent users from adding or removing any letters

Exploring the ACE Editor integration with AngularJS (utilizing UI-Ace). I have a question. Is it possible to limit the user's actions to: Only allow entering a predefined character (for example, ;) Prevent deletion of any characters except for the p ...

What is the best way to access details about a logged-in user in Node.js?

Is there a way to retrieve information about the currently authenticated user in Node.js (specifically Express.js), similar to using Auth::user() in Laravel framework? Appreciate any guidance on this. Thank you. ...

Dealing with HTTP upgrade within ExpressJS: A guide

ExpressJS has made a change where it no longer inherits from http.Server. When attempting to listen on the upgrade event, the server is responding with a 404 Not Found. This is a snippet of the current code: app.on('upgrade', function(req, soc ...

What could be causing my Node application to give a 404 error when making a POST request?

I'm at a loss trying to debug my app for what seems like a simple error, but I just can't locate it. Here is an overview of how my Express app is structured. My routes are set up as follows: var routes = require('./routes'); ... app.g ...

Having trouble passing AWS EMR Jupyter Notebook's socket through a node application. Unable to load kernel

We are facing an issue with our node application that serves as a proxy for the Jupyter notebook running on AWS EMR. While we can successfully proxy all HTTP requests using http-proxy-middleware, we are encountering difficulties when it comes to handling w ...

Issue with jqLite's .triggerHandler() functionality not behaving as anticipated

I'm having an issue with a piece of code that uses triggerHandler. The event is being called correctly, but it's not working as expected. Below is the code snippet and a link to a jsFiddle : HTML: <body ng-app="app"> <button box-cr ...

Running promises in sequence with Node.js

Hey there, I'm looking for a way to run promises sequentially in Node.js. In the example below, I am looping through an array of hours and want to fetch results from the database for each hour in the same order as they were retrieved. angular.forEac ...

Using Typescript alongside Angular 1.6 and browserify for your development needs

Currently navigating the world of working with Angular types in TypeScript and bundling code using Browserify. After following a TypeScript guide related to Gulp, I utilized npm to install the Angular types and put together this simple ts file. import * a ...