Angularjs dependency injection in resolve

2020-02-22 06:19发布

问题:

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'])

回答1:

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.

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

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.