Reputation: 900
I am calling some rest API(s) in my Angular app to get data from server and display it on page (ex: home page). But every time I visit the page, the API is hit, and data is fetched and displayed, because in my Controller, I am calling the rest service. Is there any 'best' way I can 'save' the data on first call and then, when user visits the same page, display the 'saved' data instead of hitting rest services again and again?
Also, there will be instances when I would want to hit the API instead of displaying saved data (ex: when user logs out and logs in again, or when data updates on server). What's the best way with Angular to implement such functionality?
Here is a working Plunker for demo of my current app. (Please see home.js for service call example).
angular.module('home').controller('HomeCtrl', function($scope, DrinkService) {
var vm = this;
vm.loading = true;
vm.greeting = "Drink World!";
DrinkService.getDrinks().then(function(response) {
vm.drinks = response.data.results;
console.log(vm.drinks);
vm.loading = false;
});
}).factory('DrinkService', ['$http',
function($http) {
var url = 'https://raw.githubusercontent.com/Randmness/DeathByCaffeine-Enyo/master/data/canonDbList_dbService.json';
var drinkService = {};
drinkService.getDrinks = function() {
return $http.get(url).then(function(response) {
return response;
});
};
return drinkService;
}
]);
Upvotes: 0
Views: 1078
Reputation: 436
@user2954587 answer will help you. I would also like to add that services are singleton i.e they are created once and hence are perfect to store data, share data among other controllers etc. Controllers on other hand are bound to a view. Each time a view is loaded controller bound to it is loaded too. You also need to remove data from the service some times(in your case when you logout), just set inject myService
to the controller where you perform the logout operation and set data
to undefined
.
Upvotes: 2
Reputation: 4861
You can use a service using $q
. An example service would be
service('myService', function($q, $http) {
this.data;
var self = this;
this.getMyData = function() {
if (angular.isDefined(self.data)) {
// use $q to return a promise
return $q.when(self.data)
}
return $http.get('myurl').then(function(resp) {
self.data = resp;
})
}
}
The service will set the value from the API the first time it's called and set the value on the service so subsequent calls use the saved data.
In your controller you can call myService.getMyData()
you can see a similar question here
Upvotes: 2