0

so I have been trying to learn about AngularJS factories to handle data outside of my controllers.. I am having a hard time with this one and could use some help, advice, or direction. so far this is what i have, but my $scope variable is not populating with data received from parse..thanks for any help...

app.factory('ParseData', function($http) {
var ParseFactory = {};

ParseFactory.getItems = function() {

    $http({method : 'GET',url : 'https://api.parse.com/1/classes/DrinkMenu/', headers: 
      { 'X-Parse-Application-Id':'xxxxxxxxxxxx',
        'X-Parse-REST-API-Key':'xxxxxxxxxx'}})
        .success(function(data, status) {
            return data;
        })
        .error(function(data, status) {
            alert("Error");
        });
    };

    return ParseFactory;

});

app.controller('OrderFormController', function($scope, ParseData) {
    $scope.items = ParseData.getItems();
});

1 Answer 1

1

Your getItems() method doesn't return anything. Your return statements return from the callback methods passed to success() and error(). But those are

  • ignored
  • executed asynchronoulsy, after the getItems() method has returned, when the response from the web service comes in.

So the code should rather be:

ParseFactory.getItems = function() {

    return $http.get('https://api.parse.com/1/classes/DrinkMenu/', { 
           headers: { 
               'X-Parse-Application-Id':'xxxxxxxxxxxx',
               'X-Parse-REST-API-Key':'xxxxxxxxxx'}
           })
        .then(function(response) {
            // transform the promise of response into a promise of data
            return response.data;
        });
};

and in the controller:

ParseData.getItems().then(function(data) {
    $scope.items = data;
}).catch(function() {
    alert('error');
});

There is no way you can transform an asynchronous call into a synchronous one. If that was possible, angular would do it and return data from $http calls instead of returning a promise. So your own service must also return a promise. And the controller must register callbacks on the returned promise.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.