简体   繁体   English

在AngularJS中将$ http或$ timeout与$ stateProvider一起使用

[英]Using $http or $timeout with $stateProvider in AngularJS

I come here from this question Is it possible to load a template via AJAX request for UI-Router in Angular? 我来自这个问题, 是否可以通过Angular中的UI-Router的AJAX请求加载模板?

I wish to load a template for a given state using $http . 我希望使用$http加载给定state的模板。

ui.router docs shows examples where both $timeout and $http are used within $stateProvider config, eg ui.router文档显示了在$stateProvider配置中同时使用$timeout$http$stateProvider ,例如

Or you can use a template provider function which can be injected, has access to locals, and must return template HTML, like this: 或者,您可以使用模板提供程序函数,该函数可以被注入,可以访问本地语言并且必须返回模板HTML,如下所示:

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

However, as I understand it, $stateProvider has to be configured during module.config phase, and $timeout is not available then. 但是,据我了解,必须在module.config阶段配置$stateProvider ,然后$timeout不可用。 I cannot find any example which shows how to access $timeout (or $http ) for $stateProvider exactly per the example provided by the docs . 我找不到任何示例,该示例完全按照docs提供的示例显示如何访问$stateProvider $timeout (或$http )。

Is there a way to access either $timeout or $http as defined in the docs? 是否可以访问文档中定义的$timeout$http Do I configure state at another point? 是否在另一点配置状态? Is there an alternative way to do this which I'm overlooking? 有我可以忽略的替代方法吗?

The templateProvider function itself is injected with the dependencies using injector service, and it has nothing to do with the config phase. 使用注入程序服务将templateProvider函数本身注入依赖项,并且与config阶段无关。

So you should be able to use $http simply by injecting it in the function. 因此,只需将$http注入到函数中就可以使用它。 If you see the example, $timeout or $stateParams are also not available at the config phase, but they work fine in the templateProvider function. 如果您看到示例,则$timeout$stateParams在配置阶段也不可用,但是它们在templateProvider函数中可以正常工作。

For example, the below snippet returns the content of HTTPBin: 例如,以下代码段返回HTTPBin的内容:

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

For more details, refer to this fiddle . 有关更多详细信息,请参阅此小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM