解决 Angularjs 依赖注入 [英] Angularjs dependency injection in resolve

查看:21
本文介绍了解决 Angularjs 依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 MyCtrl1 中使用适当的依赖注入来注入 MyCtrl1.resolve 对象的字段.我尝试了许多不同的尝试注入 @MyCtrl1.resolve 等的组合,但都没有成功.

I would like to use proper dependency injection in MyCtrl1to inject the fields of the MyCtrl1.resolve object. I've tried many different combinations of attempting to inject @MyCtrl1.resolve etc. with no luck.

@MyCtrl1 = ($scope, $http, batman, title) ->
  $scope.batman = batman.data
  $scope.title = title.data

@MyCtrl1.resolve = {
 batman: ($http) ->
   $http.get('batman.json')
 title: ($http) ->
   $http.get('title.json')
}
#@MyCtrl1.$inject = ['$scope', '$http'] -- commented out because not sure how to inject resolve fields

 angular
.module( 'app', [])
.config( ['$routeProvider', '$locationProvider', ($routeProvider, $locationProvider)->
  $locationProvider.html5Mode(true)

  $routeProvider.when('/', {templateUrl: 'index.html', controller: MyCtrl1, resolve: MyCtrl1.resolve})
  $routeProvider.otherwise({redirectTo: '/'})
])

angular.bootstrap(document,['app'])

推荐答案

Resolve 是路由的属性,而不是控制器.控制器将被注入在路由级别定义的依赖项,无需在控制器上指定解析属性.

Resolve is a property of a route and not a controller. Controllers would be injected with dependencies defined on a route level, there is no need to specify resolve properties on a controller.

以您的示例之一(转换为 JavaScript)为例,您将一如既往地定义您的控制器,即:

Taking one of your examples (transformed to JavaScript), you would define your controller as always, that is:

MyCtrl1 = function($scope, $http, batman, title) {
  $scope.batman = batman.data;
  $scope.title = title.data;
}

然后是路由上的 resolve 属性:

and then the resolve property on a route:

angular.module('app', []).config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
  $locationProvider.html5Mode(true)

  $routeProvider.when('/',{templateUrl: 'index.html', controller: MyCtrl1, resolve: {
    batman: ['$http', function($http) {
      return $http.get(..).then(function(response){
         return response.data;
      });
    }],
    title: ['$http', function($http) {
      return //as above
    }]
  }});
  $routeProvider.otherwise({redirectTo: '/'});
}]);

如果您想使用路由的解析部分来缩小代码,您需要使用数组样式的注释 - 我已将其包含在上面的示例中.

If you want to minify the code using resolve section of routing you need to use array-style annotations - I've included this in the example above.

这篇关于解决 Angularjs 依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆