Javascript 关于AngularJS$RouteParams

Javascript 关于AngularJS$RouteParams,javascript,angularjs,Javascript,Angularjs,我刚开始学AngularJS。当我使用AngularJS的.service时,如果我注入$RouteParams,但我实际上没有使用$RouteParams,那么.service就不起作用了 myApp.service('myService', function() { this.name = 'myServiceName'; var self = this; this.nameLength = function () { return self.name

我刚开始学AngularJS。当我使用AngularJS的
.service
时,如果我注入
$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
的使用?

问题不在于
$RouteParams
而在于注入的依赖顺序。交换依赖项的顺序,使其与带注释的依赖项相同。在您的代码中,您在
myService
之前对
$routeParams
服务进行了注释:
['$scope'、'$log'、'$routeParams'、'myService'
但是当在注入的Dependencies中使用它们作为回调函数参数时,您在
myService
之后使用了
$routeParams
。当您尝试使用
myService.name
时,它实际上指的是
$routeParams
,它没有名为
name的属性ode>。按如下所示更改您的代码,它将正常工作

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

像这样创建你的控制器。这种方式不那么混乱,更具可读性

myApp.controller('mainController', function($scope, $log,myService,$routeParams) {
    $scope.handle = myService.name;
});

Aditya Singh已经很好地解释了这一点。为了防止出现此错误,您可以将代码样式更改为:

myApp.controller('mainController',
['$scope', '$log', '$routeParams', 'myService',
function($scope, $log, $routeParams, myService) {
    $scope.handle = myService.name;
}]);

这还可以防止在控制器中有许多注入时进行垂直滚动。

这是“隐式注释”。引自:“小心:如果你计划缩小代码,你的服务名称将被重命名并破坏你的应用程序。”这没有错,但不是最佳做法。是的……这是不利的一面。谢谢阿迪蒂亚,它可以工作!这是正确的AngularJs到底是如何实现依赖注入的,这让我很困惑。我将继续学习!