gpt4 book ai didi

javascript - 使用 ui 路由器时在应用程序配置中使用 $http 服务

转载 作者:行者123 更新时间:2023-11-28 08:51:37 26 4
gpt4 key购买 nike

我在项目中使用 Angular ui 路由器和 coachpotato,我希望 ui 路由器状态从服务器端加载并添加到 Angular app.Config 中的状态提供程序,但无法将 $http 服务注入(inject) app.Config 函数,我的代码如下这:

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();
}]);

如何在app.Config中从服务器获取数据(状态)

最佳答案

底线是:

  • 您无法将服务注入(inject)提供程序配置部分。
  • 您可以将服务注入(inject)到初始化提供者服务的部分。

详细信息:

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

第 1 阶段:配置

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

第 2 阶段:运行

run阶段,所有run部分都会被执行。在此阶段提供者已准备就绪并可以创建服务 -> 在运行阶段您可以使用/注入(inject)服务。

示例:

<强>1。将 $http 服务注入(inject)提供程序初始化函数将不起作用

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 服务注入(inject)到 config 阶段执行的函数中,因此我们将收到错误:

Uncaught Error: Unknown provider: $http from services 

这个错误实际上说明的是用于创建 $http 服务的 $httpProvider 尚未准备好(因为我们仍处于 >配置阶段)。

<强>2。将 $http 服务注入(inject)到服务初始化函数中将会起作用:

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;
};
});

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

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

关于javascript - 使用 ui 路由器时在应用程序配置中使用 $http 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19078279/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com