Angularjs如何切换路由时取消资源的承诺 [英] Angularjs how to cancel resource promise when switching routes

查看:118
本文介绍了Angularjs如何切换路由时取消资源的承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始湿Angularjs我的脚。我有我觉得有一些做的承诺的问题。

I'm just getting my feet wet with Angularjs. I have an issue which I think has something to do with promises.

比方说,我加载路线A,这使得一些Ajax请求通过它的控制器:

Let's say I load route 'A' which makes several ajax requests through it's controller:

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请求通过它的控制器:

Then I have route 'B' which makes it's own API request through it's controller:

$scope.categories = Category.query();

下面是目前使用的路由工厂服务'A':

Here's the factory service currently used by route 'A':

.factory('AllSites',function($resource){
    return $resource('api/categorySites/:id');
});

当我第一次视图route'A',但然后切换到之前AB完成加载,路线'B'坐着的一切最初要求在'A'等待完成(实际上,查询()提出要求,但它不会解决,直到一个'A'确实,在这一点上,在。然后东东()继续发生,即使我因为我现在在另一条路线并不需要它。

When I first view route 'A' but then switch to 'B' before 'A' is finished loading, route 'B' sits and waits for everything initially requested in 'A' to finish (actually, the query() request is made, but it won't resolve until the one from 'A' does, at that point, the stuff inside .then() continues to happen, even though I don't need it as I'm now on another route.

正如你可以在我的devtools时间表看到,绿线表示,当我切换到路径'B'。路由'B'的要求并没有解决,直到上述两个要求做(这通常是非常快的请求)。 (在这一点上,我能够使用视图的用户)。然后,在这之后,更多的承诺,从路线'A'解决。

As you can see in my devtools timeline, the green line indicates when I switched to route 'B'. The request for route 'B' didn't resolve until the two requests above did (a request that is usually very fast). (at which point I'm able to use the view as a user). Then, after that, more promises resolve from route 'A'.

我到处去寻找一个答案,只能找到想推迟的路线,直到装载承诺得到解决的人。但在我的情况下,我几乎要相反。我想,当我切换到杀死这些请求。

I've searched everywhere for an answer and can only find people that want to "defer" the route loading until promises are resolved. But in my case I almost want the opposite. I want to kill those requests when I switch.

下面是别人用相同的,悬而未决的问题:拒绝Angularjs资源承诺

Here's someone else with the same, unanswered question: Reject Angularjs resource promises

任何帮助是AP preciated。

Any help is appreciated.

推荐答案

首先,我决定我需要使用 $ HTTP ,因为我无法找到任何解决办法所用 $资源,也不能我得到它在我自己的工作。

First of all, I decided I needed to use $http since I couldn't find any solution that used $resource, nor could I get it to work on my own.

因此​​,这里就是我的工厂变成的基础上,@希德的答案在这里,使用在<一个导向href=\"http://www.bennadel.com/blog/2616-aborting-ajax-requests-using-http-and-angularjs.htm\">http://www.bennadel.com/blog/2616-aborting-ajax-requests-using-http-and-angularjs.htm

So here's what my factory turned into, based on @Sid's answer here, using the guide at 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')

Then, in my controller (route 'A' from my problem):

var allSitesPromise = AllSites.getSites(categoryID);

$scope.$on('$destroy',function(){
    allSitesPromise.abort();
});

allSitesPromise.then(function(allSites){
    // do stuff here with the result
}

我希望厂家不那么凌乱,但我会采取什么我可以得到的。不过,现在有一个独立的,相关的问题<一href=\"http://stackoverflow.com/questions/24457367/angularjs-aborted-promises-still-delay-other-promises\">Here在那里,虽然承诺被取消,接下来的操作仍然受到延误。如果你有一个答案,你可以在那里张贴。

I wish the factory wasn't so messy, but I'll take what I can get. However, now there's a separate, related issue Here where, though the promise was cancelled, the next actions are still delayed. If you have an answer for that, you can post it there.

这篇关于Angularjs如何切换路由时取消资源的承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆