AngularJS 延迟加载的 routeProvider 使用来自 WebAPI 的值

AngularJS routeProvider with lazy loading to use values from WebAPI

我有一个延迟加载各种模块的 routeProvider。我的实现基于这两篇文章:

https://codereview.stackexchange.com/questions/42581/dynamic-routing-with-lazy-load-controllers http://ify.io/lazy-loading-in-angularjs/

它看起来像这样并且工作得很好:

myApp.config(function ($routeProvider) {

    $routeProvider.
    when('/', {
        templateUrl: 'templates/startpage.html',
        controller: 'startPageController',
    }).
    otherwise({
        resolve: {
            deps: function ($q, $rootScope, $location) {
                var deferred = $q.defer();
                var path = $location.path();
                var modulename = $location.path().split("/")[1];
                if (modulename != null) {
                    var scriptfile = '/Scripts/' + modulename + 'controller.js';
                    $script(scriptfile, function () {
                        $rootScope.$apply(function () {
                            //reprocess the route
                            $rootScope.$broadcast('$locationChangeSuccess', path, path);
                        });
                    });
                }
                return deferred.promise;
            }
        }
    });
});

现在我想根据从 WebAPI 返回的值检查 modulename 变量。如果 modulename 的值不在返回的数组中,我希望将 AngularJS 重定向到根 (/)。

我尝试在 deps 函数中注入 $http,但在那里使用它会导致它被加载多次。这也不是很有效,因为数据应该被检索一次然后使用结果。但是,我无法找到一种方法从 deps 函数之外的 WebAPI 检索数据(因为无法将 $http 注入 myApp.config)。

我如何着手更改 myApp.config 以从 WebAPI 获取批准的 "modules" 列表,然后使用此列表生成路由?

我最终使用了完全不同的东西。

因为每个路由都在每个模块的控制器中定义,所以我使用 WebAPI 获取所有可用的模块,然后我延迟加载该模块的控制器,它设置了正确的路由。我在 AngularJS 应用程序的 run 方法中执行此操作,因为它可以访问 $http 变量。

这是结果:

myApp.config(function ($routeProvider) {
    $routeProvider.
    when('/', {
        templateUrl: 'templates/startpage.html',
        controller: 'startPageController',
    }).
    otherwise({
        redirectTo: '/'
    });
});

myApp.run(function($http) {
    $http.get('/webapi/modules').success(function(data) {
        angular.forEach(data, function (module, key) {
            var scriptfile = '/Scripts/' + module + 'controller.js';
            $script(scriptfile, function () {});
        });
    });
});

可能不是最优雅或最复杂的解决方案,但它确实有效。