In AngularUI Router, do unresolved promise leak?

2019-04-01 12:13发布

问题:

I am using angular UI router and I was wondering if anyone knew whether or not unresolved promises when using resolve would leak. Our use case is that in certain states, we needed to do some checks and then transition to a different url before the original state loads.

The way we handled this was doing the check and switching the url using $location inside resolve and leaving an unresolved promise. The unresolved promise was used to prevent the original state's controllers and templates from loading (or else they would've thrown errors).

So my question is, does this practice of leaving unresolved promises cause leakage? I realize an alternative option is to set a long $timeout for resolving the promises but if its not necessary, I would like to avoid it.

回答1:

You would need to resolve or reject the promise. I would suggest that the URL switching would take place in the $stateChangeError event listener, which would be fired by rejection of the promise. You can pass the location you want to go to in the reject([data]) to the listener.

http://fiddle.jshell.net/L9jxf/2/

Some promise that will reject after a timeout (simulates server call)

        protected: ['$timeout', '$q', function ($timeout, $q) {
            var deferred = $q.defer();
            $timeout(function () {
                deferred.reject({type:'redirect',location:'401'});
            }, 1000);
            return deferred.promise;
        }]

This handles the rejection

app.run(function ($rootScope, $state) {
    $rootScope.$on('$stateChangeError', function (e, to, toParams, from, fromParams, error) {
        if (error.type === 'redirect') {
            $state.transitionTo(error.location);
        }
    });
});