Store information in factory and then use it

Hi to everyone!

I am new in Ionic I trying to figure out some things. I just start coding few months ago, so be patient with me.
What I am trying to achieve is store the information of an API response, I already created the factory and it is working perfectly.

But my concern is that as I use a Free API I cannot have to many request, so each time the user clicks somewhere I am calling to this API and making a request and reponse. The API is a forecast weather for the next 36 hours, and what I want is to store the information and use it later for than once. I have 4 different buttons that takes to different information and templates, that’s why I need to store it somewhere to use it later.
Only when the user search a new city it will make a new request (this is handled by a click and search, so it is not a problem).

I hope my english is not bad and you all understand me.

Sounds like you want to use caching.

1 Like
angular.module('myapp').factory('api', ['$http', '$q', function($http, $q) {

	var cache = {
		customers: {}
	};

	// get customers
	service.getCustomers = function() {

		var deferred = $q.defer();
		
		if (cache.customers) {
			deferred.resolve(cache.customers);
		}
		else {
			$http({
				method: 'GET',
				url: "url.com",
			}).then(
			function (response) {
				var data = response.data;
				cache.customers = data;
				deferred.resolve(cache.customers);
			},
			function (response) {
				deferred.reject('Server error');
			}
			);
		}
		

		return deferred.promise;
	}


	return service;

}]);


// in controller
api.getCustomers($scope.article.atorp_artnr).then(
	function (data) {
		$scope.customers = data;
	},
	function (errorText) {				
		$scope.customersError = errorText;
	});

Sounds exactly what I was looking for, I’ll take a look.