AngularJS - 确定视图是否应在路由更改时通过 ajax 调用结果显示 [英] AngularJS - Determine if the view should be displayed by an ajax call result upon the route changes

查看:22
本文介绍了AngularJS - 确定视图是否应在路由更改时通过 ajax 调用结果显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单来说,我想在显示某些路由的视图之前检查会话是否还活着(这意味着用户已经登录),如果不是,则重定向到登录视图.

To put it simple, I would like to check out that if the session is still alive (which means user has logged in) before displaying the view of some routes, if not, then redirect to log-in view.

我尝试从登录页面内部监听 $routeChangeStart 事件,该事件最初默认显示,但用户仍然可以通过输入路由进入其他视图.

I have tried to listen to $routeChangeStart event from inside the log-in page, which is displayed initially by default, but user can still go to other views by typing in the routes.

现在我正在做的是:

(function() {
    'use strict';

    angular.module("appClubS", ["appClubS.userModule", "appClubS.productModule", "clubsServices", "ngRoute", "ui.bootstrap"])
        .config(routeConfigurator);

    angular.module("appClubS")
        .controller("checkLoginCtrl", checkLoginController);

    checkLoginController.$inject = ['$scope', '$rootScope', '$location', 'userFactory'];
    routeConfigurator.$inject = ['$routeProvider', '$locationProvider'];

    function routeConfigurator($routeProvider, $locationProvider) {
        $routeProvider.when("/home", {
            templateUrl: "views/index.html"
        });

        // ...

        $routeProvider.when("/account-profile/my-redeem", {
            templateUrl: "views/member_zone/my.redeem.html",
            controller: 'checkLoginCtrl'
        });

        $routeProvider.when("/account-profile/my-survey", {
            templateUrl: "views/member_zone/my.survey.html",
            controller: 'checkLoginCtrl'
        });

    }

    function checkLoginController($scope, $rootScope, $location, userFactory) {
        var loginStatus = userFactory.loggedin();

        if (!loginStatus) {
            alert('Please Login First!');
            $location.path('/login');
        }
    }

})();

但在用户导航到登录页面之前,视图仍会显示.

But the view still gets displayed before user is navigated to log-in page.

有人可以帮忙吗?非常感谢.

Could anyone help? Thanks so much in advance.

推荐答案

您可以使用解析函数

 $routeProvider.when("/home", {
            templateUrl: "views/index.html",
            resolve:{
              checkLogin: function (sessionService) {
              sessionService.redirectIfLogged();
              }
            }
        });

这样可以确保在渲染视图之前运行您的检查

So this ensures your check is runned before the view is rendered

这篇关于AngularJS - 确定视图是否应在路由更改时通过 ajax 调用结果显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆