Angular - $q.all()

Angular - $q.all()

by Nirvanachain

HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-rc.2/angular.min.js"></script>
<div ng-app="myApp">
    <div ng-controller="MainCtrl">
        <h3>{{title}}</h3>
        <ul>
            <li ng-repeat="person in people">
                {{person.name}} - {{person.state}} - {{person.employeed}}
            </li>
        </ul>
    </div>
</div>

JavaScript

var myApp = angular.module('myApp', []);

myApp.controller('MainCtrl', function($scope, myService) {
    $scope.title = 'My title';
    
    myService.getObjects()
    .then(function(response) {
        console.log('response =',response);
        $scope.people = response;
    });
    
});

myApp.service('myService', function($q, $http) {
    return {
        getObjects: getObjects
    };
    
    function getObjects() {
        var url_1 = 'https://api.mongolab.com/api/1/databases/test-1/collections/test-collection?apiKey=qcVNgNb-s1X4WJkLeRDfykxqtMG-ezkC';
        var url_2 = 'https://api.mongolab.com/api/1/databases/test-2/collections/test-collection?apiKey=qcVNgNb-s1X4WJkLeRDfykxqtMG-ezkC';
        var get_1 = $http.get(url_1);
        var get_2 = $http.get(url_2);
        
        return $q.all([get_1, get_2])
                       .then(function(arr) {

                           var dataArr = arr.map(function(item) {
                               return item.data[0]; //Array so get the first object out.
                           });
                           
                           return dataArr;
                       });
    }
                       
});