我的ApiService:
app
.factory('apiService', apiService);
apiService.$inject = ['$http'];
function apiService($http) {
return {
get: _get,
post: _post
};
function _get(url, config) {
return $http.get(url, config);
}
function _post(url, data, config) {
return $http.post(url, data, config);
}
}
我的图书服务:
app
.factory('bookService', bookService);
bookService.$inject=['SERVER_CONSTANT','BOOK_CONSTANT','apiService'];
function bookService(SERVER_CONSTANT,BOOK_CONSTANT,apiService) {
return {
getLowestOnlinePrice:_getLowestOnlinePrice
}
function _getLowestOnlinePrice(isbn){
return apiService.get("......");
}
}
我的控制器:
function doSearch(data){
angular.forEach($scope.bookSearchResult,function(book){
book.lowestOnlinePricePromise =
bookService.getLowestOnlinePrice(book.bookIsbn).then(function(response){
...
}).catch(function(response){
...
});
});
}
function onClick(){
angular.forEach($scope.bookSearchResult,function(resultBook){
console.log(resultBook.lowestOnlinePricePromise);
//prints as Promise Object
});
angular.forEach($scope.bookSearchResult,function(resultBook){
resultBook.lowestOnlinePricePromise.resolve();
// Shows Error resolve is not a function
});
}
我必须停止正在进行的http请求。当我打印承诺时,它们打印为Promise
对象。现在如何阻止他们?我没有在apiService
上使用$q.defer()
。我不确定什么是最好的方法。尝试了resolve()
,但显示为resultBook.lowestOnlinePricePromise.resolve is not a function
。需要帮助。
我使用的是版本1.4.5
谢谢你的建议。
使GET
&POST
在apiService
中的功能与此类似
function _get(url, config) {
var defer = $q.defer();
var promise = $http.get(url, { timeout: defer.promise});
promise.abort = function(reason){
defer.resolve(reason);
};
return promise;
}
然后在控制器上:
function doSearch(data){
angular.forEach($scope.bookSearchResult,function(book){
(book.lowestOnlinePricePromise =
bookService.getLowestOnlinePrice(book.bookIsbn)).then(function(response){
...
}).catch(function(response){
...
});
});
}
function onClick(){
angular.forEach($scope.bookSearchResult,function(resultBook){
resultBook.lowestOnlinePricePromise.abort();
});
}
在该解决方案中,promise
中添加了一个abort()
函数。然后,唯一的承诺被保存在控制器上。
再次查找
(book.lowestOnlinePricePromise = bookService.getLowestOnlinePrice(book.bookIsbn)).then()
只要需要,只需调用abort()
函数。
找到帮助:http://www.bennadel.com/blog/2616-aborting-ajax-requests-using-http-and-angularjs.htm