AngularJS $routeProvider Resolve Method Not Workin

2020-05-06 08:30发布

问题:

In my code, I define the following two routes:

    $routeProvider.when('/problem/report', {
        templateUrl: '/app/management/problem/reportAProblem.html',
        controller: 'reportAProblemCtrl',
        resolve: {
            authorized: function($http, $location) {
                var path = $location.path();
                return $http.get('/svc/authorize/view?urlPath=' + path).then(function(response) {
                    var data = response.data;
                    if (response.data.result === 'NOT_AUTHORIZED') {
                        throw "NOT_AUTHORIZED";
                    }

                    return data;
                })
            }
        }
    });

    $routeProvider.when('/problem', {
        templateUrl: '/app/management/problem/problem.tmpl.html',
        controller: 'problemCtrl',
        resolve: {
            authorized: ['$authorization', function($authorization) {
                $authorization.authorize(); 
            }]
        }
    });

The first case seems to work. However, the second case has had the function refactored into a Service, and AngularJS does not seem to be waiting for the Promise to resolve before displaying the page.

The refactored code looks like the following:

angular.module('authorization', [])
.factory('$authorization', ['$http', '$location',function($http, $location) {

    var $authorization = {};

    $authorization.authorize = function() {

        var path = $location.path();
        return $http.get('/svc/authorize/view?urlPath=' + path).then(function(response) {
            var data = response.data;
            if (response.data.result === 'NOT_AUTHORIZED') {
                throw "NOT_AUTHORIZED";
            }

            return data;
        });
    }

    return $authorization;
}]);

Can anyone tell me why the second case above doesn't wait for the promise to resolve before displaying the page?

回答1:

Add return:

authorized: ['$authorization', function($authorization) { **return** $authorization.authorize(); }]