AngularJS:我如何解决TypeError:eventService.test不是一个函数

时间:2016-02-10 15:20:19

标签: javascript .net angularjs asp.net-mvc angularjs-scope

运行我的应用程序时收到此错误消息。我看不出我的代码有什么问题。我有一个简单的控制器调用service.js文件中的函数。并且警报消息是灯塔,所以它意味着代码被执行,但是我得到TypeError错误,为什么?

我的控制器看起来像是:

(function () {
"use strict";

angular.module('myApp.EventController', [])

 .controller('EventController', ['$scope', '$http', 'eventService', EventController]);

function EventController($scope,$http, eventService) {

        $scope.loading = true;
        $scope.addMode = false;
        $scope.events = [];


        eventService.test().then(function () {
           // $scope.loading = false;
        }, function (error) {
           // $scope.error = "Feilet ved opplasting av event!" + error.data.message;
        });

        $scope.toggleEdit = function () {
            this.event.editMode = !this.event.editMode;
        };

        //by pressing toggleAdd button ng-click in html, this method will be hit
        $scope.toggleAdd = function () {
            $scope.addMode = !$scope.addMode;
        };
    }

}());

Service.js看起来像是:

(function () {
"use strict";
angular.module('myApp.eventService', [])

.service('eventService', ['$http', 'ngAuthSettings', eventService]);

function eventService($http, ngAuthSettings) {

    var serviceBase = ngAuthSettings.apiServiceBaseUri;
    alert('ServiceBase: ' + serviceBase)
    this.test = function () {
        alert('Test funker...')
    };
}

}());

1 个答案:

答案 0 :(得分:0)

您必须返回服务中声明的函数,然后才能调用控制器

var app = angular.module('myApp.eventService');

app.service('eventService', function ($http) {
    return {
        test: function () {
            console.log('Test function');
        },
        //another:function(){}
    }
});