$http is a core service in Angularjs that reads data from a remote server. In Angularjs's actual project, multiple $http requests are often processed, each $http request returns a promise, and we can put multiple promise into an array argument accepted by the $q.all () method.
1. Handle 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}}})}} yservice.getuserevents = function getuserevents () {...} Myservice.getall = function () {var userpromise = Myservice.getdat
A (), usereventspromise = Myservice.getuserrepos (), userrepospromise = Myservice.getuserrepos (); Return $q. All ([Userpromise, Usereventspromise, Userrepospromise]). Then (function (){
....
}) }
})
2. $http Request Cache
$http Get method The second parameter accepts an object, and the cache field of the object can accept a bool type implementation cache, that is, {cache:true}, or it can accept a service.
Create a service by factory and inject the service into the 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");
}
)
Small Series Summary:
In fact, the caching mechanism is implemented by $cachefactory
Put the caching mechanism in the current request through {Cache:mycache}
$cacheFactory the request API as a key, so clear caching is also based on this key to clear the cache
The above is a small set for everyone to share in the Angularjs $http caching and processing a number of $http requests, I hope to help.