OllyBarca OllyBarca - 1 year ago 75
AngularJS Question

$http request in angular config - Is it possible?

I am trying to make an $http call inside my publicApp.config in order to retrieve an array of available routes to match with the $urlMatcherFactoryProvider.

Right now, I am hard-coding them to be

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

But I have an url in my express API which returns an array of available URLS. The api URL is

Would it be possible to make an
request inside the config? I know $http is available inside
, but I need the list of available URLs BEFORE 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 + ")}");

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




Answer Source

Create a provider which gets $stateProvider as an injectable. The provider will create a service that does the http request then registers the routes. Inject the service in a run block and initiate route registration.

Something like this:

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

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

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