避免多次Ajax请求angularJS [英] Avoid multiple ajax requests angularJS
问题描述
我试图避免多次Ajax请求在工厂的服务器。我已经添加了一个小的缓存服务,但它是不够的,我的目标是:在服务器响应之前,这个工厂可以被称为多次,造成多次请求到服务器的产生。
要避免这一点,我添加了第二个承诺对象,如果AJAX请求已经被执行,对象是尚未在缓存中,比它应该等待第二承诺解决,但看起来像我失去了一些东西。
这是我的code:
myApp.factory('用户',['Restangular','$ Q',
功能(Restangular,$ Q){
VAR userCache,alreadyRun = FALSE;
返回{
的getUser:功能(){
变种推迟= $ q.defer(),firstRun = $ q.defer(); 如果(userCache&安培;!&安培;!alreadyRun){
alreadyRun = TRUE; Restangular.all(用户)的GetList()。然后(功能(用户){
的console.log('获取用户现场);
userCache =用户[0] .email;
firstRun.resolve(用户[0] .email);
});
}否则如果(userCache&安培;!&安培; alreadyRun){
的console.log('等待第一个承诺要解决');
firstRun.then(功能(用户){
的console.log('解决的承诺');
deferred.resolve(userCache);
}); }其他{
的console.log('解决从缓存中的承诺');
deferred.resolve(userCache)
}
返回deferred.promise;
}
};
}
]);
您可以只归还当初的诺言,如果请求已经作出。像这样的东西应该工作;
myApp.factory('用户',['Restangular','$ Q',
功能(Restangular,$ Q){
VAR递延= FALSE; 返回{
的getUser:功能(){ 如果(延期){
返回deferred.promise;
} 递延= $ q.defer(); Restangular.all(用户)的GetList()。然后(功能(用户){
deferred.resolve(用户[0] .email);
}); 返回deferred.promise;
}
};
}
]);
也有看 Restangular文档
I am trying to avoid multiple ajax requests to the server in a factory. I already added a small caching service, but it is not enough for what I aim: this factory can be called several times before the server responds, causing the generation of multiple requests to the server.
To avoid this I added a second promise object, which if the AJAX request have been performed and the object is not yet in cache, than it should wait for a second promise to be resolved, but looks like I am missing something.
This is my code:
myApp.factory('User', ['Restangular', '$q',
function (Restangular, $q) {
var userCache, alreadyRun = false;
return {
getUser: function () {
var deferred = $q.defer(), firstRun= $q.defer();
if (!userCache && !alreadyRun) {
alreadyRun = true;
Restangular.all('user').getList().then(function (user) {
console.log('getting user live ');
userCache = user[0].email;
firstRun.resolve(user[0].email);
});
} else if (!userCache && alreadyRun) {
console.log('waiting for the first promise to be resolved ');
firstRun.then(function(user) {
console.log('resolving the promise');
deferred.resolve(userCache);
});
} else {
console.log('resolving the promise from the cache');
deferred.resolve(userCache)
}
return deferred.promise;
}
};
}
]);
You could just return the original promise if the request has already been made. Something like this should work;
myApp.factory('User', ['Restangular', '$q',
function (Restangular, $q) {
var deferred = false;
return {
getUser: function () {
if(deferred) {
return deferred.promise;
}
deferred = $q.defer();
Restangular.all('user').getList().then(function (user) {
deferred.resolve(user[0].email);
});
return deferred.promise;
}
};
}
]);
Also have a look at the Restangular documentation for caching requests
这篇关于避免多次Ajax请求angularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!