AngularJS: Getting factory returned data in controller

Has a factory that makes multiple API calls that are tied to a single promise, when I return a promise to my controller, I cannot get the data from the object returned by the 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)

});

      

Unable to get data from $ scope.uacForm object.

+3


source to share


1 answer


$scope.uacForm

will be your promise, not the actual value. You need to put the data somewhere in the scope when the promise is resolved in order to be able to get it from the view. Those.



factory1.getData().then(function(data, status, headers, config)
{
    $scope.uacForm = data.data2;
    console.log($scope.uacForm)
},
function(data, status, headers, config)
{
    alert("Error")
})

      

+2


source







All Articles