Angular ui-router cannot resolve $resource results

2020-04-10 01:15发布

In one of my UI-router states, I have the following link '/users', which points to a page that shows a list of users. Below is the code I wrote to resolve the list of users by using a $resource call, however, the data doesn't seem resolved when the page is loaded:

.state('users', {
                    url: '/users',
                    templateUrl: '/assets/angularApp/partials/users.html',
                    controller: 'UserListCtrl as vm',
                    resolve: {

                        users: function ($resource) {

                            return $resource('http://localhost:8080/api/users').query().$promise.then(function(data) {
                                return data;
                            });
                        }
                    }


                })

In the UserListCtrl, I have the following to assign the resolved users to vm.users so that the users can be displayed on the partial page:

function UserListCtrl($log, users) {
        var vm = this;
        vm.users = users;
}

The page, however, only displays a few empty rows without any data filled in. So I think the resolve is not working properly on my url /users, could anyone spot where might be problematic? Thanks

2条回答
别忘想泡老子
2楼-- · 2020-04-10 01:36

Change it to:

users: function ($resource) {
    return $resource('http://localhost:8080/api/users').query().$promise;
}

Because that way you're returning the promise, and by using then(...), you're resolving the promise within and just returning data thus it won't pass it to the controller because it's returning them after the controller has loaded.

查看更多
Anthone
3楼-- · 2020-04-10 01:38

Using $q service will help you

var userVal = $resource('http://localhost:8080/api/users').query()
retrun $q.resolve(userVal.$promise).then(function(r){ return r;});

Inside you controller, you are good to go

vm.users = users
查看更多
登录 后发表回答