[英]How to call a specific promise only once in Angular 1.5 when onInit hook is called multiple times
我在onInit函数上进行了一个API调用。
vm.$onInit = function() {
var callInProgress = false;
var resultsLoaded = false;
var url = '/api/times/cst';
if(callInProgress === false && resultsLoaded ===false){
callInProgress = true;
HttpWrapper.send(url,{"operation":'GET'}).then(function(result){
vm.times = result;
resultsLoaded = true;
},function(error){
vm.errorInApi = true;
});
}
现在$onInit
被多次调用,因此每次初始化两个标志callInProgress, resultsLoaded
。
因此,检查有点不起作用。
每次调用$onInit
,都会多次调用API。
我怎么只能打一次电话? 虽然它已在$onInit
上$onInit
。
我建议将API调用包装在以下服务中:
(function (angular) {
'use strict';
angular
.module('services.common')
.service('TimesService', TimesService);
TimesService.$inject = ['HttpWrapper'];
function TimesService(HttpWrapper) {
var timesService = this;
var timesResult = null;
timesService.getTimes = getTimes;
function getTimes() {
if (!timesResult) {
timesResult = HttpWrapper.send('/api/times/cst', {"operation": 'GET'});
}
return timesResult;
}
return timesService;
}
})(angular);
然后将其注入到控制器中,并使用类似TimesService.getTimes().then(...)
,因此对API的调用只会在第一次调用TimesService.getTimes
进行一次(因为结果将存储在timesResult
内部的timesResult
)。
callInProgress和resultsLoaded在onInit函数内,并且是指令控制器的一部分。 每次使用指令时,它们都会被创建。 使用包含控制器上的controller属性来执行类似的操作。 您可以使用绑定来指定控制器属性,以使其保持某种通用性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.