angularjsangular-promiseroute-provider

$routeProvider resolve is not getting object from promise


I am having trouble trying to get an array of objects from a promise. I have two issues. First, when the GetAccounts() gets called in the AccountService, it returns 2 objects. In the resolve, when I check the variable result, it doesn't have the 2 objects. Second, when the controller gets instantiated, it gives me this error: accounts is not defined. Can anyone tell me what I am doing wrong? Thanks in advance.

AccountService.js

app.factory('AccountService', ['$http', function ($http) {
    return {
        GetAccounts: function () {
            return $http.get('api/Account/GetAccounts')
            .then(function success(response) {
                return response.data;
            }, function error(response) {
                return console.log("Oops!");
            });
        }
    };
}]);

AdminController.js

app.component('admin', {
    templateUrl: 'Content/app/components/admin/Admin.html',
    bindings: {
        accounts: '<'
    },
    controller: function () {
        this.accounts = accounts;
    }
})

route.js

app.config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/admin', {
        template: '<admin accounts="$resolve.GetAccounts"></admin>',
        resolve: {
            GetAccounts: ['AccountService', function (AccountService) {
                var result = AccountService.GetAccounts();

                return result;
            }]
        }
    })
}]);

Solution

  • Make the following changes to get it works.

    AdminController.js

    app.component('admin', {
        templateUrl: 'Content/app/components/admin/Admin.html',
        bindings: {
            accounts: '<'
        }    })
    

    route.js

    app.config(['$routeProvider', function ($routeProvider) {
        $routeProvider.when('/admin', {
            template: 'template.html',
            resolve: {
                GetAccounts: ['AccountService', function (AccountService) {
                    var result = AccountService.GetAccounts();
    
                    return result;
                }]
            },
            controller:['$scope','GetAccounts',function($scope, GetAccounts){
               $scope.accounts = GetAccounts;
            }]
        })
    }]);
    

    template.html

    <div>
    <admin accounts="accounts"></admin>
    </div>