AngularJS $routeProvider Resolve Method Not Workin

2020-05-06 08:25发布

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条回答
2楼-- · 2020-05-06 08:53

Add return:

authorized: ['$authorization', function($authorization) { **return** $authorization.authorize(); }]
查看更多
登录 后发表回答