Chris G
Chris G

Reputation: 245

AngularJS factory with Parse.com database

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();
});

Upvotes: 0

Views: 464

Answers (1)

JB Nizet
JB Nizet

Reputation: 691755

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.

Upvotes: 1

Related Questions