Kenny Kenny - 4 months ago 23
AngularJS Question

Angularjs Controller calling Service - .success if not a function

I'm using a controller to call a service that will make an

$http
request, but right now I've only set my service to return a string because I want to make sure it works and is calling properly.

When I run it, I get the following error:

TypeError: monitorData.requestEvent(...).success is not a function


My code below:

Controller

(function() {

angular
.module('monitorApp')
.controller('eventCtrl', eventCtrl);

eventCtrl.$inject = ['$scope', '$routeParams', 'monitorData'];
function eventCtrl($scope, $routeParams, monitorData) {
var vm = this;
vm.eventid = $routeParams.eventid;
vm.event = {};

vm.getData = function(eventid) {
console.log("getData variable accessed");
monitorData.requestEvent(eventid)
.success(function(data) {
console.log(data);
})
.error(function(e) {
console.log("Error");
});
return false;
};

vm.getData(vm.eventid);

}

})();


Service

(function() {

angular
.module('monitorApp')
.service('monitorData', monitorData);

monitorData.$inject = ['$http'];
function monitorData($http) {
var requestEvent = function(eventid) {
var gas = "Event " + eventid + " requested.."
console.log(gas);
return gas;
};

return {
requestEvent : requestEvent,
};
}

})();

Answer

In order to be chained, it should return a settled promise.

monitorData.$inject = ['$http', '$q'];
function monitorData($http, $q) {
    var requestEvent = function(eventid) {
        var gas = "Event " + eventid + " requested.."
        console.log(gas);
        return $q.resolve(gas);
    };

    return {
        requestEvent : requestEvent,
    };
}

And by the way, success and error are deprecated legacy methods. It is always then and catch now.