JSON list on master-page, details on detail-page

I have a script which gets data from a mysql database in a JSON-file. I would like to list these items and navigate to the details of the selected option. Everything works fine when I put the data statically in a variable, but it doesn’t work when I parse the json file with $http.get()

service.js

angular.module('starter.services', [])

.factory('RequestService',function(){
  
  var requests = [ 
  {
        "id": "1",
        "firstname": "Steve",
        "lastname": "Jobs",
        "allowance": "56",
        "employeeid": "1",
        "date": "2014-11-19 12:18:00",
        "picture": "pic",
        "startdate": "2014-11-12",
        "enddate": "2014-11-12",
        "type": "Ilness",
        "reason": "My back hurts",
        "notes": "The doctor said: 'You should rest!'",
        "function": "Director",
        "status": "Pending",
        "comment": ""
    }    
    ];
    return {
        getRequests: function(){ 
        		console.log(requests);
                return requests;
        },
        getRequest: function(id){
            for(i=0;i<requests.length;i++){
                if(requests[i].id == id){
                    return requests[i];
                }
            }
        }
    }
})

controllers.js

.controller('masterCtrl', function($scope, RequestService) {
$scope.requests = RequestService.getRequests();
})

.controller('detailsCtrl', function($scope, $stateParams, RequestService) {
  $scope.request = RequestService.getRequest($stateParams.requestId);
})

So far, it works!

But if I replace the services.js file with the following, it doesn’t work anymore:

angular.module('starter.services', [])
  
.factory('RequestService', function($http) {
	var requests = [];
    return {
        getRequests: function(){ 
            return $http.get("url/to/getrequests.php").then(function(response){
                requests = response.data;
                console.log(requests);
                return requests;
            });
        },
        getRequest: function(id){
            for(i=0;i<requests.length;i++){
                if(requests[i].id == id){
                    return requests[i];
                }
            }
        }
    }
})

Can anyone help me please?

Thanks in advance!

Jan

The controller is returned a $q promise, not the Array yet.
So, you need to wrap the controller side of getRequests() accordingly. The $q is probably not needed, just showing it to underline what we actually are dealing with (promises).

.controller('masterCtrl', function($q, $scope, RequestService) {
  RequestService.getRequests().then(function(data){
    	$scope.requests = data;
    	console.log($scope.requests);
	})
  })

Plus, I’d use the $http .success and .error methods instead of the more genric $q method .then at the service side.

1 Like

Thanks, this works!