ホームページ  >  記事  >  ウェブフロントエンド  >  AngularJS での $http キャッシュと複数の $http リクエストの処理方法の詳細な説明_AngularJS

AngularJS での $http キャッシュと複数の $http リクエストの処理方法の詳細な説明_AngularJS

WBOY
WBOYオリジナル
2016-05-16 15:16:091501ブラウズ

$http は AngularJS のコア サービスであり、リモート サーバーからデータを読み取るために使用されます。実際の AngularJS プロジェクトでは、多くの場合、複数の $http リクエストを処理する必要があります。各 $http リクエストは、$q.all() メソッドで受け入れられる配列引数に複数の Promise を入れることができます。

1. 複数の $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(){
....
})
}
})

2.$http リクエスト キャッシュ

$http の get メソッドの 2 番目の仮パラメータはオブジェクトを受け入れます。オブジェクトのキャッシュ フィールドは、キャッシュを実装するための bool 型 (つまり、{cache:true}) を受け入れることができます。また、サービスを受け入れることもできます。

ファクトリ メソッドでサービスを作成し、そのサービスをコントローラーに挿入します。

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 をキーとして使用するため、キャッシュをクリアするときは、このキーに基づいてキャッシュもクリアします

上記は、エディターで共有した、AngularJS での $http キャッシュと複数の $http リクエストの処理方法です。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。