AngularJS $routeProvider Resolve Method Not Working

Issue

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?

Solution

Add return:

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

Answered By – Petr Averyanov

Answer Checked By – Pedro (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.