如何设置超时以中止工厂或服务中的$ http.get()? [英] How to set a timeout to abort an $http.get() inside a factory or service?
问题描述
我的工厂中具有以下方法getData(url)
,该方法使用$http.get(url)
从URL获取数据
I have the following method getData(url)
in a my factory which uses $http.get(url)
to get data from an URL
angular
.module('az-app')
.factory('WebServiceFactory', function ($http, $q) {
var WebServiceFactory = this;
WebServiceFactory.getData = function (url) {
var deferred = $q.defer();
$http.get(url)
.then(
function (response) {
deferred.resolve({
data: response
});
}, function (rejected) {
deferred.reject({
data: rejected
});
}
);
//Promise to be returned
return deferred.promise;
}
它工作正常,但是我需要中止http.get和/或拒绝诺言,这样我才能显示具有此方法的控制器的错误消息:
It works fine but I need to abort the http.get and/or reject the promise so I can display an error message from my controller which has this method:
var getSpecialties = function (type) {
doctorsCtrl.showLoading();
var url = "example.com";
WebServiceFactory.getData(url)
.then(
function (result) {
doctorsCtrl.hideLoading();
var specialtiesArray = result.data.data;
StorageFactory.specialties = specialtiesArray;
doctorsCtrl.specialties = StorageFactory.specialties
//I WANT TO TRIGGER THIS REJECTED FUNCTION when timeout time is finished
}, function (rejected) {
doctorsCtrl.hideLoading();
doctorsCtrl.showAlert();
}
);
}
推荐答案
服务$http
在config对象中接受timeout
属性,该属性可以满足您的需求.看看文档,尤其是关于config
对象的部分:
The service $http
accepts, in the config object, a timeout
property that answers to what you need. Have a look at the documentation, especially the part about the config
object:
timeout – {number | Promise} –超时(以毫秒为单位),或承诺应在解决后中止请求.
timeout – {number|Promise} – timeout in milliseconds, or promise that should abort the request when resolved.
另外,请注意,您以低效的方式使用了Promise.以下是 承诺反模式 :
Also, notice that you're using promises in an inefficient way. The following is a promise antipattern:
WebServiceFactory.getData = function (url) {
var deferred = $q.defer();
$http.get(url)
.then(
function (response) {
deferred.resolve(...);
}, function (rejected) {
deferred.reject(...);
}
);
//Promise to be returned
return deferred.promise;
}
您可以简单地做到:
WebServiceFactory.getData = function (url) {
return $http.get(url);
}
超时为3秒将是:
服务:
WebServiceFactory.getData = function (url) {
return $http.get(url, {timeout: 3000}); // <-- timeout applies ONLY for this call
}
控制器:
WebServiceFactory.getData(url).then(
function (result) {
doctorsCtrl.hideLoading();
doctorsCtrl.specialties = StorageFactory.specialties = result.data;
}, function (rejected) {
doctorsCtrl.hideLoading();
doctorsCtrl.showAlert();
}
);
还请注意,如果成功和错误,您都在呼叫hideLoading
.您可以在链接的最终处理程序中调用一次:
Notice also that you're calling hideLoading
both in case of success and error. You can call it once, in a chained finally handler:
// ...
.finally(function () {
doctorsCtrl.hideLoading();
}
这篇关于如何设置超时以中止工厂或服务中的$ http.get()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!