here is a piece of code I am struggling with - I have a controller (zmApp.MonitorCtrl) that is calling a factory (ZMFactory) with an HTTP request.
The problem I am facing is this: a) When the controller calls ZMFactory.getMonitors() it returns undef and I get an error ERROR: Error: undefined is not an object (evaluating 'ZMFactory.getMonitors().then')
b) After this error comes up, the http request in the factory is processed
I am a little confused. Can you please check if the factory has been set up correctly to return a promise?
var app = angular.module('zmApp.controllers');
app.controller('zmApp.MonitorCtrl', function($ionicPlatform, $scope,$http,ZMFactory)
{
$scope.monitors=[];
console.log("***CALLING FACTORY");
ZMFactory.getMonitors().then(function(data)
{
$scope.monitors = data;
console.log ("I GOT " +$scope.monitors);
});
});
app.factory('ZMFactory',['$http', '$rootScope',function($http,$rootScope)
{
//var factory = {};
var monitors =[];
return {
getMonitors: function()
{
console.log("***MAKING REQUEST");
$http({
url:'http://myurl.com:9999/zm/index.php?skin=xml',
method:'post',
headers: {'Content-Type': 'application/x-www-form-urlencoded',
'Accept': '*/*',
},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
var foo= str.join("&");
console.log ("****RETURNING "+foo);
return foo;
},
transformResponse: function(data)
{
var x2js = new X2JS();
var json = x2js.xml_str2json(data);
console.log ("***Transmogrifying XML to JSON");
return json;
},
data: {username:'xxx',
password:'xxxx',
action:'login',
view:'console'}
}) //http
.success (function(data)
{
console.log("****YAY"+JSON.stringify(data));
var subobj =data.ZM_XML.MONITOR_LIST.MONITOR;
var len = subobj.length;
for (var i =0; i< len; i++)
{
console.log ("HERE " + subobj[i].NAME);
monitors.push(subobj[i]);
}
// $rootScope.$broadcast ('handleZoneMinderMonitorsUpdate',monitors);
return monitors;
}) //success
.error(function(data, status, headers, config)
{
console.log("***OOPS "+status + " H: "+data);
return monitors;
});
} //getMonitors
};//return
console.log ("**** NEVER *****");
}]);
return $http({ ...}); then you could handle.then(onSuccess, onError)in the controller. but it is probably better to research and create your own promise wrapping the entire http req/rep