我刚刚和Angularjs擦肩而过。我有一个问题,我认为这与承诺有关。
我们说我加载路线' A'通过它的控制器发出几个ajax请求:
allSites = AllSites.query({ id:categoryID });
allSites.$promise.then(function(allSites){
//add stuff to the scope and does other things
//(including making another ajax request)
});
然后我有路线' B'通过它的控制器使其成为自己的API请求:
$scope.categories = Category.query();
以下是路线目前使用的工厂服务' A':
.factory('AllSites',function($resource){
return $resource('api/categorySites/:id');
});
当我第一次看到路线' A'但然后切换到' B'之前' A'已完成装载,路线' B'坐下来等待最初要求的所有事情。' A'完成(实际上,查询()请求已经完成,但它不会解决,直到来自“A'”之后,.then()
内的内容继续发生,即使我不需要它,因为我现在正在另一条路上。
正如您在我的devtools时间轴中所看到的,绿线表示我何时切换到路线' B'。路线请求' B'在上述两个请求之前没有解决(请求通常非常快)。 (此时我可以将视图用作用户)。然后,在此之后,更多的承诺将从路线A'。
解决
我到处寻找答案,只能找到想要推迟的人。路由加载直到承诺得到解决。但就我而言,我几乎想要相反。我想在切换时杀死这些请求。
在这里,其他人有同样的,未回答的问题:Reject Angularjs resource promises
感谢任何帮助。
答案 0 :(得分:14)
首先,我决定使用$http
,因为我无法找到使用$resource
的任何解决方案,也无法让它自行运行。
所以,根据@ Sid的答案,使用http://www.bennadel.com/blog/2616-aborting-ajax-requests-using-http-and-angularjs.htm
上的指南,我的工厂变成了什么.factory('AllSites',function($http,$q){
function getSites(categoryID) {
// The timeout property of the http request takes a deferred value
// that will abort the underying AJAX request if / when the deferred
// value is resolved.
var deferredAbort = $q.defer();
// Initiate the AJAX request.
var request = $http({
method: 'get',
url: 'api/categorySites/'+categoryID,
timeout: deferredAbort.promise
});
// Rather than returning the http-promise object, we want to pipe it
// through another promise so that we can "unwrap" the response
// without letting the http-transport mechansim leak out of the
// service layer.
var promise = request.then(
function( response ) {
return( response.data );
},
function() {
return( $q.reject( 'Something went wrong' ) );
}
);
// Now that we have the promise that we're going to return to the
// calling context, let's augment it with the abort method. Since
// the $http service uses a deferred value for the timeout, then
// all we have to do here is resolve the value and AngularJS will
// abort the underlying AJAX request.
promise.abort = function() {
deferredAbort.resolve();
};
// Since we're creating functions and passing them out of scope,
// we're creating object references that may be hard to garbage
// collect. As such, we can perform some clean-up once we know
// that the requests has finished.
promise.finally(
function() {
promise.abort = angular.noop;
deferredAbort = request = promise = null;
}
);
return( promise );
}
// Return the public API.
return({
getSites: getSites
});
});
然后,在我的控制器中(路线' A'来自我的问题):
var allSitesPromise = AllSites.getSites(categoryID);
$scope.$on('$destroy',function(){
allSitesPromise.abort();
});
allSitesPromise.then(function(allSites){
// do stuff here with the result
}
我希望工厂不是那么凌乱,但我会把我能得到的东西弄得一团糟。但是,现在有一个单独的相关问题Here,虽然承诺被取消,但下一步行动仍然会延迟。如果你有答案,你可以在那里发布。
答案 1 :(得分:2)
答案中有一个类似的问题" How to cancel $resource requests"。
虽然它没有完全解决这个问题,但是当切换路线时它会取消所有成分来取消资源请求:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Cancel resource</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular-resource.js"></script>
<script>
angular.module("app", ["ngResource"]).
factory(
"services",
["$resource", function($resource)
{
function resolveAction(resolve)
{
if (this.params)
{
this.timeout = this.params.timeout;
this.params.timeout = null;
}
this.then = null;
resolve(this);
}
return $resource(
"http://md5.jsontest.com/",
{},
{
MD5:
{
method: "GET",
params: { text: null },
then: resolveAction
},
});
}]).
controller(
"Test",
["services", "$q", "$timeout", function(services, $q, $timeout)
{
this.value = "Sample text";
this.requestTimeout = 100;
this.call = function()
{
var self = this;
self.result = services.MD5(
{
text: self.value,
timeout: $q(function(resolve)
{
$timeout(resolve, self.requestTimeout);
})
});
}
}]);
</script>
</head>
<body ng-app="app" ng-controller="Test as test">
<label>Text: <input type="text" ng-model="test.value" /></label><br/>
<label>Timeout: <input type="text" ng-model="test.requestTimeout" /></label><br/>
<input type="button" value="call" ng-click="test.call()"/>
<div ng-bind="test.result.md5"></div>
</body>
</html>
请查看&#34; Cancel Angularjs resource request&#34;详情。
答案 2 :(得分:1)
答案 3 :(得分:0)
我用$ q.reject()取消了这个承诺。我认为这种方式更简单:
在SitesServices.js中:
;(() => {
app.services('SitesServices', sitesServices)
sitesServices.$inject = ['$http', '$q']
function sitesServices($http, $q) {
var sitesPromise = $q.defer()
this.getSites = () => {
var url = 'api/sites'
sitesPromise.reject()
sitesPromise = $q.defer()
$http.get(url)
.success(sitesPromise.resolve)
.error(sitesPromise.reject)
return sitesPromise.promise
}
}
})()
在SitesController.js中:
;(() => {
app.controller('SitesController', sitesControler)
sitesControler.$inject = ['$scope', 'SitesServices']
function sitesControler($scope, SitesServices) {
$scope.sites = []
$scope.getSites = () => {
SitesServices.getSites().then(sites => {
$scope.sites = sites
})
}
}
})()
答案 4 :(得分:0)
检查$resource
的文档我找到了这个小美女的链接。
https://docs.angularjs.org/api/ng/service/ $ HTTP#使用
timeout - {number | Promise} - 超时(以毫秒为单位),或承诺 应该在解决时中止请求。
我已经成功地使用了它。它有点像这样。
export default function MyService($q, $http) {
"ngInject";
var service = {
getStuff: getStuff,
};
let _cancelGetStuff = angular.noop;
return service;
function getStuff(args) {
_cancelGetStuff(); // cancel any previous request that might be ongoing.
let canceller = $q( resolve => { _cancelGetStuff = resolve; });
return $http({
method: "GET",
url: <MYURL>
params: args,
timeout: canceller
}).then(successCB, errorCB);
function successCB (response) {
return response.data;
}
function errorCB (error) {
return $q.reject(error.data);
}
}
}
请记住
successCB
,但response
为undefined
。error.status
将-1
就像请求超时一样。