3

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.

1 Answer 1

2

$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")
})
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks, but I need to have the data outside the function.How should i get it outside the above function.
you can't. that's how you use promises.
okay,then how come I can bind the returned variable to ng-model and access the same in HTML?
because angular sees it's a promise and handles it accordingly.
could you please tell me how to use that returned variable in view(HTML)?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.