AngularJS |刷新浏览器时,angularjs 模板在安全上下文之前加载。如何阻止它?

AngularJS | On refreshing the browser, angularjs templates load before the security context. How to stop it?

在我的 angularjs 应用程序中(使用 angular-ui),在刷新浏览器时,在获取安全上下文之前加载特定状态的模板从服务器。 获取安全上下文的 $http 调用被命中,但由于它是异步的,因此尚未设置。

解决这个问题的最佳方法是什么?

此外,我一直在努力做到以下几点:

//on the state change event from refresh

$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){
    console.log("state change has started");
    if(fromState.name === '' && fromState.url === '^'){
        console.log("inside state change from refresh");
        //what needs to be done in this block to let the security context is fetched (should I use $timeout etc.) ?
           .........
           .........
    }
});

event.preventDefault(); 

在你的 if 块中。它将停止状态更改。然后通过安全检查后,您可以

$state.go(toState, toParams);

但这是错误的方法。就像@Radim 建议的那样,你必须使用 resolve.

我们使用以下两个代码片段来解决这个问题。在我们结束这里之前,我们尝试了其他几种方式。这个好像还挺给力的。。。

在用户服务工厂中:

     // setup UserService OBject
    ...
    // bootstrap the Service 
    var tokenRetrieved = $location.search().token || localStorageService.get(AUTH_COOKIE_NAME);

    if (tokenRetrieved) {
                UserService.login(tokenRetrieved, true)
                    .then(function success(user) {
                        UserService.initialized = true;
                    }, function error(err) {
                        localStorageService.remove(AUTH_COOKIE_NAME);
                        UserService.initialized = true;
                    });
    } else {
          UserService.initialized = true;
    }

    return UserService;

并且在 $stateChangeStart 处理程序中:

            if (UserService.initialized) {
                // here we check authorization for the toState
                ....


            } else {
                // if the UserService is not done initializing we cancel the stateChange and schedule it again in 200ms
                event.preventDefault();
                $rootScope.$log.log('preventing state change, because UserService not ready to check Authorization');
                $timeout(function () {
                    $state.go(toState, toParams);
                }, 200);
            }