使用 UI 路由器时$http应用配置中使用服务



>我在项目中使用 Angular UI 路由器和 Coach Potato,我希望 UI 路由器状态从服务器端加载并添加到 Angular 应用程序中的状态提供程序。配置,但无法将$http服务注入应用。配置函数,我的代码是这样的:

var app = angular.module('app', [ 'ui.router.compat']);
app.config(['$stateProvider', '$routeProvider', '$urlRouterProvider', '$http',
  function ($stateProvider, $routeProvider, $urlRouterProvider, $http) {
      $urlRouterProvider
        .when('/c?id', '/contacts/:id')
        .otherwise('/');
      $routeProvider
        .when('/user/:id', {
            redirectTo: '/contacts/:id'
        });
      var get = $http.get('/api/Values/');
      get.success(function (data) {
            list = data.result;
        });
      var populateStates = function () {
          angular.forEach(list, function(item) {
              $stateProvider.state(item);
              angular.forEach(item.subMenus, function(sub) {
                  $stateProvider.state(sub);
              });
          });
      };
      populateStates();
  }]);

如何在应用程序中从服务器获取数据(状态(。配置

底线是:

  • 您不能将服务注入提供程序配置部分。
  • 您可以将服务注入到初始化提供程序服务的部分中。

详:

Angular 框架有一个 2 阶段的初始化过程:

阶段 1:配置

config阶段,将初始化所有提供程序,并执行所有config部分。config部分可能包含配置提供程序对象的代码,因此可以将它们注入提供程序对象。但是,由于提供程序是服务对象的工厂,并且在此阶段提供程序尚未完全初始化/配置 ->您不能要求提供程序在此阶段为您创建服务 ->在配置阶段您不能使用/注入服务。完成此阶段后,所有提供程序都已准备就绪(配置阶段完成后,无法再进行提供程序配置(。

第 2 阶段:运行

run阶段将执行所有run部分。在此阶段,提供程序已准备就绪,可以创建服务 ->在运行阶段,您可以使用/注入服务。

例子:

1. 将$http服务注入提供程序初始化函数将不起作用

angular.module('myModule').provider('myProvider', function($http) {
    // SECTION 1: code to initialize/configure the PROVIDER goes here (executed during `config` phase)
    ...
    this.$get = function() {
        // code to initialize/configure the SERVICE goes here (executed during `run` stage)
        return myService;
    };
});

由于我们尝试将$http服务注入到config阶段执行的函数中,因此将出现错误:

Uncaught Error: Unknown provider: $http from services 

这个错误实际上是在说,用于创建$http服务的$httpProvider尚未准备就绪(因为我们仍处于config阶段(。

2. 将$http服务注入服务初始化函数将起作用:

angular.module('myModule').provider('myProvider', function() {
    // SECTION 1: code to initialize/configure the PROVIDER goes here (executed during `config` phase)
    ...
    this.$get = function($http) {
        // code to initialize/configure the SERVICE goes here (executed during `run` stage)
        return myService;
    };
});

由于我们现在将服务注入到服务初始化函数中,该函数run阶段执行,因此此代码将起作用。

注意:这是从这里无耻地复制的

最新更新