我刚开始学习AngularJS。当我使用.service of AngularJS时,如果注入$RouteParams,但实际上不使用$RouteParams,那么.service就不能工作。
myApp.service('myService', function() {
this.name = 'myServiceName';
var self = this;
this.nameLength = function () {
return self.name.length;
};
});
myApp.controller('mainController', ['$scope','$log','$routeParams','myService',function($scope, $log,myService,$routeParams) {
$scope.handle = myService.name;
}]);奇怪的是,如果我在控制器中使用$RouteParams,那么为什么$RouteParams会影响.service的使用?
发布于 2016-05-29 08:13:30
问题不在于$routeParams,而在于注入依赖关系的顺序。交换依赖项的顺序,使其与带注释的依赖项相同。在您的代码中,您已经在myService:['$scope','$log','$routeParams','myService'之前对['$scope','$log','$routeParams','myService'服务进行了注释,但是当将它们作为回调函数参数使用时,您将在myService之后使用$routeParams。当您尝试使用myService.name时,它实际上是指没有名为name的属性的$routeParams。按下面的方式更改您的代码,它将工作
myApp.service('myService',function(){
this.name='myServiceName';
var self=this;
this.nameLength=function(){
return self.name.length;
};
});
myApp.controller('mainController', ['$scope','$log','$routeParams','myService',function($scope, $log,$routeParams, myService) {
$scope.handle = myService.name;
}]);发布于 2016-05-29 08:25:33
像这样创建控制器。这种方式不那么让人困惑,也更容易读懂。
myApp.controller('mainController', function($scope, $log,myService,$routeParams) {
$scope.handle = myService.name;
});发布于 2016-05-29 08:25:37
阿迪娅·辛格已经很好地解释了这一点。若要防止此错误,可以将代码样式更改为:
myApp.controller('mainController',
['$scope', '$log', '$routeParams', 'myService',
function($scope, $log, $routeParams, myService) {
$scope.handle = myService.name;
}]);当控制器中有许多注入时,这也防止了垂直滚动。
https://stackoverflow.com/questions/37507585
复制相似问题