I wrote the following factory service in AngularJS, but when I try to call the factory service in my RootController, I got the "undefined is not a function" error in my console.
MyService.js:
(function() {
angular.module('serviceTestApp')
.factory('MyService', ['$resource', '$log', '$q', '$http', MyService]);
function MyService($log, $resource, $http, $q) {
var name = "Tom";
var getName = function() {
return name;
}; //getName
var changeName = function(newName) {
name = newName;
}; //changeName
var getIP = function() {
var deferredObj = $q.defer();
$resource('http://jsonip.com').query().$promise.then(function(result) {
deferredObj.resolve(result);
}, function(errorMsg) {
deferredObj.reject(errorMsg);
});
return deferredObj.promise;
}; //getIP
return {
getName: getName,
changeName: changeName,
getIP: getIP
};
}
}());
in my RootController, I try to call the services, and everything worked until I call the getIP() service - return a promise object. Does anyone see anything wrong?
RootController.js:
(function() {
angular.module('serviceTestApp')
.controller('RootCtrl', ['$http', '$log', '$scope', 'MyService', RootCtrl]);
function RootCtrl($log, $scope, $http, MyService) {
var vm = this;
vm.message = "hello world from RootController";
MyService.changeName("Henry Tudor");
vm.message = "my name is: " + MyService.getName();
MyService.getIP().query().then(function(data) {
$log.info('in the promise, ip is: ' + data.ip);
vm.message = vm.message + ', your IP is ' + data.ip;
}, function(error) {
vm.message = vm.message + ', error: ' + error;
});
}
}());
MyService.getIP()is returning a promise. Promise API does not have aquery()function call - docs.angularjs.org/api/ng/service/$q