提供“角服务”;TypeError:无法读取属性'helloConsole'“未定义”;

Angular services giving "TypeError: Cannot read property 'helloConsole' of undefined"

本文关键字:未定义 读取 属性 helloConsole 服务 角服务 TypeError 提供      更新时间:2023-09-26

我正在学习AngularJS服务,遇到了一个问题。

这是我的角度代码:

var app = angular.module("todoListApp");
app.controller('MainController', MainController);
MainController.$inject = ['$scope'];
function MainController($scope, dataService){ 
    $scope.helloConsole = dataService.helloConsole;
};
app.service('dataService', function(){
    this.helloConsole = function(){
        console.log("console services");
    };
});
That's my HTML Code
<div ng-controller="MainController" class="list">
<div class="item" ng-class="{'editing-item' : editing, 'edited': todo.edited}" ng-repeat="todo in todos">
        <div class="actions">
            <a href="" ng-click=" editing = !editing">Edit</a>
            <a href="" ng-click="helloConsole()">Save</a>
            <a href="" class="delete">Delete</a>
        </div>
</div> 
</div>

我试图让它,当我点击保存时,控制台显示我"控制台服务",但它给了我一个错误:

angular.js:13424类型错误:无法读取未定义的属性"helloConsole"

适当的角度结构

您需要更改编写代码的方式。它看起来应该更像这个

angular.module("todoListApp", [])
.controller('MainController', ['$scope', 'dataService', function($scope, dataService){
    $scope.helloConsole = dataService.helloConsole;
}])
.service('dataService', [function(){
    this.helloConsole = function(){
        console.log("console services");
    };
}]);

这也是一个"数据服务",这是用http调用获取数据吗?因为如果是这样,那就造一个工厂。

  • 业务逻辑控制器
  • 数据请求的工厂
  • 登录等服务
  • DOM操作指令
  • 格式过滤器

angular.service的第二个函数参数返回一个singleton服务对象。此外,如果你明确你的控制器的依赖性,思考会更清晰/更好:

var app = angular.module("todoListApp", []);
app.controller('MainController', ['$scope', 'dataService', MainController]);
function MainController($scope, dataService){ 
    $scope.helloConsole = dataService.helloConsole;
    $scope.todos = [{txt:"todo 1"}, {txt:"todo 2"}];
}
app.service('dataService', function(){
    return {
      helloConsole: function(){
        console.log("console services");
      }
    };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.js"></script>
<div ng-app="todoListApp">
<div ng-controller="MainController" class="list">
  <div class="item" ng-class="{'editing-item' : editing, 'edited': todo.edited}" ng-repeat="todo in todos">
    {{todo.txt}}
    <div class="actions">
      <a href="" ng-click=" editing = !editing">Edit</a>
      <a href="" ng-click="helloConsole()">Save</a>
      <a href="" class="delete">Delete</a>
    </div>
  </div> 
</div>
</div>

我稍微重写了一下,这样更容易理解(至少对我来说)。我在代码中添加了一个"todos"数组,只是为了让ng重复激发。

var app = angular.module("todoListApp",[])
.service('dataService', function(){
this.helloConsole = function(){
    console.log("console services");
};
})
.controller('MainController', [ '$scope', 'dataService',function ($scope,dataService) {
 $scope.helloConsole = dataService.helloConsole;
 $scope.todos = [ {
    "todo":"1"
 }
 ]
}])
;