Details the $http cache in AngularJS and how to handle multiple $http requests

  • 2020-12-16 05:50:27
  • OfStack

$http is a core service in AngularJS for reading data from remote servers. In real AngularJS projects, you often need to process more than one $http request, and each $http request returns one promise. We can put multiple promise into an array argument accepted by the $q.all () method.

1. Process multiple $http requests


angular.module('app',[])
.controller('AppCtrl', function AppCtrl(myService){
var app = this;
myService.getAll().then(function(info){
app.myInfo = info;
})
})
.service('myService', function MyService($http, $q){
var myService = this;
user = 'https://api...',
repos = '',
events = '';
myService.getData = function getData(){
return $http.get(user).then(function(userData){
return {
name:userData.data.name,
url:userData.data.url,
repoCount: userData.data.count
}
})
};
myService.getUserRepos = function getUserRepos(){
return $http.get(repos).then(function(response){
return _.map(response.data, function(item){
return {
name: item.name,
description:item.description,
starts: item.startCount
}
})
})
}
myService.getUserEvents = function getUserEvents(){
...
}
myService.getAll = function(){
var userPromise = myService.getData(),
userEventsPromise = myService.getUserRepos(),
userReposPromise = myService.getUserRepos();
return $q.all([userPromise, userEventsPromise, userReposPromise]).then(function(){
....
})
}
})

$http request cache

The second parameter of the get method of $http accepts an object whose cache field can accept either an bool type implementation cache, i.e. {cache:true}, or a service.

Create a service with factory and inject it into controller.


angular.module('app',[])
.factory("myCache", function($cacheFactory){
return $cacheFactory("me");
})
.controller("AppCtrl", function($http, myCache){
var app = this;
app.load = function(){
$http.get("apiurl",{cache:myCache})
.success(function(data){
app.data = data;
})
}
app.clearCache = function(){
myCache.remove("apiurl");
}
})

Summary of this site:

● It's actually $cacheFactory that implements the caching mechanism
● The caching mechanism is placed in the current request through {cache:myCache}
● $cacheFactory requests api as key, so when clearing the cache, the cache is also cleared according to this key

The above is the $http cache and how to handle multiple $http requests in AngularJS shared by this site.


Related articles: