Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS : Getting factory returned data in controller

Am having a factory which makes multiple API calls which are bind to single promise, when I return the promise to my controller am not able to get the data from the object returned by a function in the controller.

Code:

Factory:

app.factory('factory1',function($http,$q){

var formData = {}
var URL = "/xxx/"
var dataToPass = {}

formData.getData = function()
{
    var data1 = $http.get(URL+'api1/')
    var data2 = $http.get(URL+'api2/')
    return $q.all({'data1':data1,'data2':data2})
}
return formData
});

Controller:

app.controller('controller1', function($scope, factory1) {
$scope.uacForm =factory1.getData().then(function(data, status, headers, config)
{
    console.log(data['data2'])
},
function(data, status, headers, config)
{
    alert("Error")
})
console.log($scope.uacForm)

});

Am not able to get the data from $scope.uacForm object.

like image 595
mithu Avatar asked Nov 27 '25 17:11

mithu


1 Answers

$scope.uacForm will just be your promise, not the actual value. You need to put the data somewhere on the scope when the promise is resolved to be able to reach it from the view. Ie

factory1.getData().then(function(data, status, headers, config)
{
    $scope.uacForm = data.data2;
    console.log($scope.uacForm)
},
function(data, status, headers, config)
{
    alert("Error")
})
like image 200
Tetaxa Avatar answered Nov 29 '25 08:11

Tetaxa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!