UI 路由器:是否可以解析子状态中的父承诺

UI-Router: Can I resolve a parent promise in a child state?

本文关键字:状态 承诺 路由器 是否 可以解 UI      更新时间:2023-09-26

我正在开发社交应用程序,它在个人资料页面中有一个封面。"编辑"和"访问"页面都有封面,但子部分不同。问题在于,封面中显示的某些控制器严格取决于您当前访问的部分。

为了解决这个问题,我尝试在父状态的解析部分中返回一个承诺,然后在不同的子状态中解析承诺。

.state('profile', {
    url: '/profile',
    controller: 'ProfileController',
    templateUrl: 'components/profile/profile.html',
    resolve: {
        actor: function(UserService){
            return UserService.getUser();
        },
        target: function($q){
            var deferred = $q.defer();
            return deferred.promise;
        }
    }
})
.state('profile.view', {
    url: '/:userId',
    templateUrl: 'components/profile/view.html',
    navbar: true,
    parent: 'profile',
    resolve: {
        /**
         *
         * @param target
         * @param {UserService} UserService
         */
        target: function(target, UserService){
            target.resolve(UserService.getActions('view'));
        }
    }
})

不幸的是,我的逻辑有问题,因为配置文件状态中的return deferred.promise阻止了应用程序。

谁能帮我弄清楚我做错了什么?

最好!

将承诺返回给解析器函数

.state('profile.view', {
    url: '/:userId',
    templateUrl: 'components/profile/view.html',
    navbar: true,
    parent: 'profile',
    resolve: {
        /**
         *
         * @param target
         * @param {UserService} UserService
         */
        target: function(target, UserService){
            return UserService.getActions('view').$promise;
        }
    }
})

此答案假定UserService$resource查询。其他 API 返回承诺的方式不同,但原理是相同的。将承诺返回到解析器函数。