问题描述
我的服务(工厂)进行 API 调用并将响应数据分配给变量:
My service (factory) makes an API call and assigns response data to a variable:
.factory('MedicationMatchingNamesFactory',
['$http', '$q', 'MedicationDisplayNamesFactory',
function MedicationMatchingNamesFactory($http, $q, MedicationDisplayNamesFactory){
return {
getMatchingNames: function(inputValue){
var matches = [];
// I thought this may be set as null so I'm able to
// differentiate it from the below array form (when exists)
var allNames = null;
MedicationDisplayNamesFactory.getDisplayNames().then(
function(response){
// this is the large dataset - now as array
var allNames = response.data.displayTermsList.term;
angular.forEach(allNames, function(value, key){
if(value.indexOf( inputValue ) !== -1){
matches.push(value);
}
});
}
);
return matches;
}
};
return MedicationMatchingNamesFactory;
}])
我正在使用 Angular-UI 的ui-select"指令根据输入的字符串在这个大型数据集中进行搜索.
I'm using Angular-UI's "ui-select" directive to search within this large dataset based on entered string.
在我的控制器中:
$scope.$on('inputStarted', function(event, value){
if(value.length > 3){
$scope.meds.displayNames = MedicationMatchingNamesFactory.getMatchingNames(value);
console.log($scope.meds.displayNames);
}
});
现在,为了避免每次输入字符数大于 3 时都查询 API(实际上调用另一个包含对 API 调用的服务),我认为如果我能够检查 allNames
是 null
(空,调用 API)或者它是一个 array
(跳过调用,直接使用).
Now, to avoid querying the API (actually call another service containing the call to API) every time the number of input characters is greater than 3, I think it would be great if I'm able to check whether allNames
is null
(empty, do call API) or it's an array
(skip the call, just use that).
我尝试将 angular.forEach
部分移到 call 和 promise 之外,但很明显,没有任何反应,因为它在第一次运行时还没有解决.
I tried moving the angular.forEach
part outside the call and promise but then, obviously, nothing happens because it's not resolved yet on the first run.
有没有办法让这个 allNames
数据集在我调用 API 之前检查?
Is there a way to have this allNames
dataset checked before I do the API call?
推荐答案
其实这个问题的解决方案很简单:我只是使用了 sessionStorage
,它似乎非常适合我在这种情况下的需求因为我需要为这次会话保留大数据集,如果它在下一个会话中丢失也没关系.目标是防止多次获取它,即不必要的获取,因为在该会话期间不太可能更改其中的值.
Actually the solution to this problem is very simple: I just went with the sessionStorage
which seems to fit perfectly my needs in this case as I need the big dataset persisted just for this session and it doesn't matter if it's lost on the next one. The goal is to prevent fetching it more than once, that is, more than necessary, as the values inside are not likely to be changed during that session.
这篇关于在我的服务工厂中,我查找了一个大型数据集 - 我想保留它并检查它是否存在以避免再次调用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!