我刚开始学习 AngularJS。当我使用 AngularJS 的 .service
时,如果我注入(inject) $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;
}]);
奇怪的是,如果我确实在 Controller 中使用了 $RouteParams
,那么它就可以工作,为什么 $RouteParams
会影响 .service< 的使用
?
最佳答案
问题不在于$routeParams
,而在于依赖注入(inject)的顺序。将依赖项的顺序互换为与注释的依赖项相同。在您的代码中,您在 myService
之前注释了 $routeParams
服务:['$scope','$log','$routeParams','myService'
但在注入(inject)的依赖项中使用它们作为回调函数参数时,您在 myService
之后使用了 $routeParams
。当您尝试使用 myService.name
时,它实际上指的是 $routeParams
,它没有名为 name
的属性。如下更改您的代码,它将起作用
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;
}]);
关于javascript - 关于 AngularJS $RouteParams,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37507585/