簡體   English   中英

Angular UI-Router-在根狀態下解析數據並在$ stateChangeStart中使用

[英]Angular UI-Router - Resolve data in root state and use in $stateChangeStart

我正在使用Angular UI-Router在前端應用程序中實現狀態。 我在抽象基本狀態上有一個resolve小組,該小組從我的所有子狀態開始擴展,但是遇到了以下問題:

我看了以下問題: 如何從$ stateChangeStart訪問UI-Router根狀態的'resolve'屬性? ...但是它並沒有真正回答我的問題。 這是代碼:

.state('app', {
    abstract: true,
    url: '/',
    templateUrl: 'build/views/layout/master.html',
    data: {
        doesRequireLogin: true
    },
    resolve: {
        principalRoles: function($q, User, RoleMapping, $rootScope) {

            var deferred = $q.defer();

            // Grab the current user, then attempt to find their roles
            User.getCurrent(
                function foundUser(user) {

                    RoleMapping.find({
                        filter: {
                            where: {
                                principalId: user.id
                            },
                            include: 'role'
                        }
                    }, function hasRoles(roleMappings) {

                        // Reduce the roles list to just the names of the roles
                        var rolesList = roleMappings.map(function(mapping) {
                            return mapping.role ? mapping.role.name : '';
                        });

                        $rootScope.user.roles = rolesList;

                        return deferred.resolve(rolesList);

                    }, function hasError(error) {
                        return deferred.reject(error);
                    });

                },
                function userError(error) {
                    return deferred.reject(error);
                }
            );
            return deferred.promise;

        }
    }
})

這工作正常,似乎返回了我需要的信息。 但是我的問題是在我的.run塊中,我有以下代碼:

// Intercept state changes to see if we need to log in
$rootScope.$on('$stateChangeStart', function (event, toState,   toParams
                                                   , fromState, fromParams) {

    console.log(arguments);

    var requireLogin = toState.data.doesRequireLogin;
    console.log(toState.data.principalRoles);

    try {
        // this only works because i assign this in the state, 
        // probably not the best idea, 
        // and besides it only works *after* the first page load, never initially
        console.log($rootScope.user.roles);
    }
    catch(e) {}

    if (requireLogin && !$rootScope.isAuthenticated) {
        event.preventDefault();
        $state.go('auth')
    }

});

這僅適用於初始頁面加載后的后續狀態更改,您能想到我如何為所有實例返回當前用戶的角色嗎?

我通過遵循Radim在以下問題中的回答來解決此問題: https : //stackoverflow.com/a/26702638/1679310

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM