Cordova Ionic注销和刷新控制器

时间:2017-01-03 18:16:08

标签: angularjs cordova ionic-framework

我一直在使用离子应用程序挣扎了很长时间。我有多个控制器,多个html页面。

每当我注销时(我使用sidemenu的控制器)我想返回第一页。每当我在第一页时,我希望能够登录其他用户。每当我在目标视图(menu.landingMenu)的UI路由器中启用cache:false时,它就不会在注销后转到该页面。

这是退出的代码。

 $scope.logOff = function () {

    appData.clear();
    $http.get(appData.hostURL + '/api/Account/logoff.aspx');
    $scope.$destroy();
    $localStorage.$reset();
    CredentialService.del();
    $state.go('login', { action: 'logoff' });
    $timeout(function () {
        $ionicHistory.clearCache();
        $ionicHistory.clearHistory();
    }, 1500)

}

这是loginController中的事件

 // Check if a state change happened
    $scope.$on('$stateChangeSuccess',
        function onStateSuccess(event, toState, toParams, fromState) {
            console.log(fromState);
            console.log('This is the Fromstrate'), fromState;
            console.log(toParams);
            if (toState.name == "login") {
                if (toParams.action == "logoff") {
                    // keep startup url (in case your app is an SPA with html5 url routing)
                    var initialHref = window.location.href;

                    function restartApplication() {


                        // Show splash screen (useful if your app takes time to load
                        // Reload original app url (ie your index.html file)

                        console.log("THis is a reload")
                        document.location.href = 'index.html';
                    }

                    restartApplication();
                } else {
                    var storedCreds = CredentialService.get()

                }
            }
        }
    );

首先,每当我退出时,按下登录页面上的提交按钮,它会“刷新”页面,它很快就会闪烁但是没有反应。

每当我第二次点击它时,它会转到下一页,但不会重新加载控制器,因此不会渲染任何数据。

1 个答案:

答案 0 :(得分:3)

代码中有几点需要改进或重构。

  • 在单页面应用中,您不想刷新页面,总是找到一种方法来清理状态,缓存等。因此,请避免使用window.location在视图之间切换以重置应用程序。 使用您所拥有的清洁功能重置状态,如:
    localStorage.clear(); CredentialService.del(); 等
  • 避免在执行函数时手动破坏范围并尝试解决缓存:false会自动执行。
  • 在输入登录或索引视图时清除ionicHistory和缓存,而不是在logOff函数内。
  • 如果需要,使用离子事件执行函数:$ ionicView.beforeEnter,$ ionicView.beforeLeave等。http://ionicframework.com/docs/api/directive/ionView/
  • 如果可能的话,Chain承诺遵循订单。

您的$ scope.logOff可能类似于:

$scope.logOff = logOff;
function logOff() {
    $http.get(appData.hostURL + '/api/Account/logoff.aspx')
         .then(clearDataAndLeave);
         .catch(someErrorFunction)
}
function clearDataAndLeave(){
    appData.clear();
    $localStorage.$reset();
    CredentialService.del();
    //other cleaning actions
    $state.go('login');    
}

在你的登录/索引控制器中:

$scope.$on("$ionicView.beforeEnter", activate);
function activate(event, data){
    $ionicHistory.clearCache();
    $ionicHistory.clearHistory();
    //Then you can handle the credentials, asking if they were deleted or something like that
    var storedCreds = CredentialService.get();
    if (storedCreds){
        //login or sthg else
    }
});