Angular ui-router cannot resolve $resource results

微笑、不失礼 提交于 2019-12-31 02:14:10

问题


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


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/28533775/angular-ui-router-cannot-resolve-resource-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!