【问题标题】:$http request in angular config - Is it possible?角度配置中的 $http 请求 - 有可能吗?
【发布时间】:2016-09-19 15:52:02
【问题描述】:

我正在尝试在我的 publicApp.config 中进行 $http 调用,以检索与 $urlMatcherFactoryProvider 匹配的可用路由数组。

现在,我将它们硬编码为pageUrls = ['about','contact','another-page'];

但是我的 express API 中有一个 url,它返回一组可用的 URL。 api地址为"/page-urls"

是否可以在配置中发出$http.get('/page-urls') 请求?我知道 $http 在 run() 中可用,但在通过 $stateProvider 路由之前,我需要可用 URL 的列表。

(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('/');


    }]);



})();

【问题讨论】:

  • 要使用 ajax 执行此操作,您需要在 angular app 之外发出请求,在 ajax 成功内手动引导应用程序而不是使用 ng-app 并从全局变量传入数据。然后它会在配置运行时可用
  • 有一个替代的router-extras 可以让你在配置之后定义路由器状态
  • 我可以在我的 Angular 应用程序之前添加一个带有 url 数组的 js 文件吗?这是一个安全的选择吗?
  • 我也打算这么建议。将最快设置并让您继续使用ng-app
  • 好吧,我正在通过后端管理应用程序动态添加页面。我想我每次添加/编辑/删除页面时都可以通过节点更新“缓存”的 js 文件。

标签: angularjs express angular-ui-router


【解决方案1】:

创建一个将$stateProvider 作为可注入的提供程序。提供者将创建一个执行 http 请求的服务,然后注册路由。在运行块中注入服务并启动路由注册。

类似这样的:

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){
                    registerRoutes(response.data);
                });
            }
        };
    };
});

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

【讨论】:

  • 我尝试了这个解决方案,但我收到一条错误消息“Uncaught TypeError: Cannot read property 'initialize' of undefined”
  • 这里是我的问题的链接:stackoverflow.com/questions/39464624/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-20
  • 1970-01-01
  • 2013-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多