gpt4 book ai didi

javascript - 在 AngularJS 中使用 $http 或 $timeout 与 $stateProvider

转载 作者:行者123 更新时间:2023-11-28 17:42:02 25 4
gpt4 key购买 nike

我是从这个问题Is it possible to load a template via AJAX request for UI-Router in Angular?来到这里

我希望使用 $http 加载给定状态的模板。

ui.router 文档显示了在 $stateProvider 配置中同时使用 $timeout$http 的示例,例如

Or you can use a template provider function which can be injected, has access to locals, and must return template HTML, like this:

$stateProvider.state('contacts', {   templateProvider: function
($timeout, $stateParams) {
return $timeout(function () {
return '<h1>' + $stateParams.contactId + '</h1>'
}, 100);
}
})

但是,据我了解,$stateProvider必须在module.config阶段配置,并且$timeout不可用。我找不到任何示例显示如何完全按照 docs 提供的示例访问 $stateProvider$timeout (或 $http)。

有没有办法访问文档中定义的 $timeout$http ?我是否要在另一点配置状态?有没有一种我忽略的替代方法可以做到这一点?

最佳答案

templateProvider函数本身是使用注入(inject)器服务注入(inject)依赖项的,与配置阶段无关。

因此,您应该只需将 $http 注入(inject)到函数中即可使用它。如果您看到示例,$timeout$stateParams 在配置阶段也不可用,但它们在 templateProvider 函数中工作正常。

例如,下面的代码片段返回 HTTPBin 的内容:

templateProvider: function($http) {
return $http.get('https://httpbin.org/get')
.then(function(response) {
return JSON.stringify(response.data);
});
}

更多详情请参阅this fiddle .

关于javascript - 在 AngularJS 中使用 $http 或 $timeout 与 $stateProvider,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47716654/

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