AngularJS $ routeProvider解决方法不起作用

时间:2019-05-28 17:52:35

标签: angularjs ngroute

在我的代码中,我定义了以下两条路线:

    $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(); 
            }]
        }
    });

第一种情况似乎有效。但是,第二种情况已将函数重构为Service,并且AngularJS在显示页面之前似乎并没有等待Promise解决。

重构后的代码如下:

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;
}]);

谁能告诉我为什么上面的第二种情况在显示页面之前不等待诺言解决?

1 个答案:

答案 0 :(得分:2)

添加回报:

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