Skip to main content
edited tags; edited title
Link
200_success
  • 145.6k
  • 22
  • 191
  • 481

Handling consecutive Returning the results of four $resource calls as a JSON array in AngularJS

Source Link
Jimenemex
  • 185
  • 1
  • 2
  • 9

Handling consecutive $resource calls in AngularJS

Title pretty much says it. I need a way to elegantly handle multiple $resource calls in AngularJS. Right now, I just calling each other call on the success function and calling a callback function to spit the data out when it's down.

Here's what I have so far.

// DataService.js
var resource = $resource('/app/data/event/:id/:ext', {id:'@id',ext:'@ext'}, {"getAll": {method: "GET", isArray: false}});
getAllEvents: function (successcb) {
    var combinedJSON = "[";
    // First Call
    var firstFile = resource.get({ id: 1, ext: '.json' });
    firstFile.$promise.then(function (data) {
        combinedJSON += JSON.stringify(data) + ",";
        // Second Call
        var secondFile = resource.get({ id: 2, ext: '.json' });
        secondFile.$promise.then(function (data) {
            combinedJSON += JSON.stringify(data) + ",";
            // Third Call
            var thirdFile = resource.get({ id: 3, ext: '.json' });
            thirdFile.$promise.then(function (data) {
                combinedJSON += JSON.stringify(data) + ",";
                // Fourth Call
                var fourthFile = resource.get({ id: 4, ext: '.json' });
                fourthFile.$promise.then(function (data) {
                    combinedJSON += JSON.stringify(data) + "]";
                    successcb(combinedJSON); // This is the success call back
                }, function (data) {
                    console.log(data);
                });
            }, function (data) {
                console.log(data);
            });
        }, function (data) {
            console.log(data);
        });
    }, function (data) {
        console.log(data);
    });
}

My callback function just spits out the data

// Controller.js
eventData.getAllEvents(function successcb(events) {
    $scope.foo = events;
});

Is there a better way to handle these types of situations?