Reputation: 12057
I have a service
that I wish to use to first grab an object from a JSON file and then to return selected data from said object, depending on what the user requests.
This service may be used multiple times per visit, so I don't wan the user to have to wait while the data is retrieved on every occasion.
I have set up the service to only request the JSON file once per page load, but I'm having some trouble extracting only the data that I wish to return.
My idea was to take a clone of the initial promise
object (referred to as promiseAll
in my code) and then manipulate the data within, before returning that cloned object (referred to as 'promiseSelected') to the user.
What I have below almost works, but if the users requests a list of type searchable
, every future request has only the results for that request.
I'm not sure what I'm doing wrong (or if there is a better way to do this), but I'd apprciate any pointers.
Here is how I am using the service
-
app.controller('searchCtrl', ['$scope', '$localStorage', '$stationsList', function($scope, $localStorage, $stationsList){
$stationsList.getList('searchable').then(function(data){
$scope.stationsList = data; // Grab a list of searchable stations
});
}]);
And here is the full service
-
app.service('$stationsList', ['$http', function($http, $scope){
var tempStations,
promiseAll,
promiseSelected;
/**
* Grab a list of the required stations
*
* @param string type The type of list to return
* @return object promiseSelected A promise object containing the stations requested by the user
*/
var getStationsList = function(type){
if(!promiseAll){
promiseAll = $http.get('stations.json').then(function(res){
return res.data; // Grab the JSON list of all stations
});
}
promiseSelected = angular.copy(promiseAll); // Take a fresh copy of 'promiseAll'
tempStations = []; // Reset to an empty array
switch(type){
case "searchable":
promiseSelected = promiseAll.then(function(data){
[].map.call(data || [], function(elm){ // Map all stations...
if (elm.link.indexOf(".xml") > -1) // Check to see if the station is searchable
tempStations.push(elm); // It is - add the station to 'tempStations'
});
return tempStations;
});
break;
case "locatable":
promiseSelected = promiseAll.then(function(data){
[].map.call(data || [], function(elm){ // Map all stations...
if(
isFinite(parseFloat(elm.latitude)) &&
isFinite(parseFloat(elm.longitude))
) // Check to see if the station is locatable
tempStations.push(elm); // It is - add the station to 'tempStations'
});
return tempStations;
});
break;
default:
promiseSelected = promiseAll;
}
return promiseSelected;
};
return{
getList: getStationsList
};
}]);
Upvotes: 0
Views: 195
Reputation: 691993
The problem is that you reuse the same tempStations
variable everywhere. This variable should be local to every function passed to then()
.
Upvotes: 1