【问题标题】:Error while using user defined service in angularjs在angularjs中使用用户定义的服务时出错
【发布时间】:2014-11-12 21:10:45
【问题描述】:

我创建了一个 angularjs 服务,我试图通过在控制器中注入服务来访问该服务。这是我使用的代码:

  angular.module('ControllerModule').controller('AwarenessCntrl',['TestService',
    function(TestService, $scope, $state)
    {
        console.log(TestService.list()[0].label);
        $scope.goToHome = function() 
        {
          $state.go('home');
        };

    }]);

我在控制台中收到以下错误消息: 错误:未定义不是对象(评估

'$scope.goToHome = function() 
    {
        $state.go('home');
    }')

这是我用于服务的代码:

angular.module('AppServices').service('TestService', [TestService]);
function TestService() {
var items = [{
    id: 1,
    label: 'Balle Balle, Service Chal Payi'
}, {
    id: 2,
    label: 'Item 1'
}];
this.list = function() {
    return items;
};
this.add = function(item) {
    items.push(item);
};
}

控制台能够打印来自服务的数据;但它也给出了我上面提到的错误消息。我到底做错了什么?

【问题讨论】:

    标签: angularjs ionic-framework


    【解决方案1】:

    您还需要在字符串数组列表中包含$scope, $state。 请参阅Angular Docs on Dependency Injection

    这里的最佳做法是先包含内置角度功能,然后再包含自定义服务。

    angular.module('ControllerModule').controller('AwarenessCntrl',['$scope', '$state', 'TestService',
        function($scope, $state, TestService)
        {
            console.log(TestService.list()[0].label);
            $scope.goToHome = function() 
            {
              $state.go('home');
            };
    
        }]);
    

    【讨论】:

    • 谢谢奥利弗。这解决了我面临的问题。
    • 太棒了 :),如果您不介意在答案中标记它,那么它将对未来的人有所帮助。
    猜你喜欢
    • 2016-08-22
    • 2012-06-03
    • 1970-01-01
    • 2015-04-29
    • 2014-11-27
    • 2013-11-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-03
    相关资源
    最近更新 更多