星空网 > 软件开发 > Java

AngularJS中的$http缓存以及处理多个$http请求

 

在AngularJS的实际项目中,经常需要处理多个$http请求,每个$http请求返回一个promise,我们可以把多个promise放到$q.all()方法接受的一个数组实参中去。

■ 处理多个$http请求

 

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请求缓存

$http的get方法第二个形参接受一个对象,该对象的cache字段可以接受一个bool类型实现缓存,即{cache:true},也可以接受一个服务。

通过factory方式创建一个服务,并把该服务注入到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");    }  })

 

以上,

● 实际上,实现缓存机制的是$cacheFactory
● 通过{cache:myCache}把缓存机制放在当前请求中
● $cacheFactory把请求api作为key,所以清楚缓存的时候,也是根据这个key来清除缓存




原标题:AngularJS中的$http缓存以及处理多个$http请求

关键词:JS

JS
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

Voghion账号:https://www.goluckyvip.com/tag/27053.html
Voilà:https://www.goluckyvip.com/tag/27055.html
volcaneestore:https://www.goluckyvip.com/tag/27056.html
Volition:https://www.goluckyvip.com/tag/27057.html
Volition Capital:https://www.goluckyvip.com/tag/27058.html
跨境制造出海:https://www.goluckyvip.com/tag/2706.html
重庆品胜科技与星苹台达成合作 助力部队现代化后勤建设 :https://www.kjdsnews.com/a/1836523.html
回乡创业,不知道干什么,能否推荐几个农村老家创业的好项目?:https://www.vstour.cn/a/365177.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流