我有一项名为SuperFactory
的服务。此服务使用fetch
方法从网址中提取一些数据。
此服务由SuperController
在我的控制器中,如何在运行时取消此HTTP请求(承诺)?
这是我的SuperFactory.js
angular
.module('app')
.factory('SuperFactory', FetchData)
function SuperFactory($http, $q, $timeout) {
return {
fetch: function(name, limit) {
var fullURL = "http://example.com?id=5;
var defer = $q.defer();
var timeoutPromise = $timeout(function() {
console.log("Timed out");
defer.reject("Timed out"); //reject the service in case of timeout
}, 10000);
var promise = $http.get(fullURL).
then(function(response) {
$timeout.cancel(timeoutPromise); //cancel the timeout
//response = cleanUpResponse(response);
response = response.data;
defer.resolve(response);
return response;
}, function(response) {
return 0;
});
return defer.promise;
}
};
}

这是我的SuperController.js
angular
.module('app')
.controller('SuperController', SuperController)
function SuperController($scope, SuperFactory, $q, $timeout, $http) {
SuperFactory.fetch()
.then(function(data) {
console.log(data);
}, function(error) {
// promise rejected
});
}