AngularJS - Determine if the view should be displa

2019-09-16 23:49发布

问题:

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.

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.

Now what I am doing is:

(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.

回答1:

You can use a resolve function

 $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