AngularJS - Determine if the view should be displayed by an ajax call result upon the route changes

戏子无情 提交于 2019-12-11 23:15:09

问题


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



来源:https://stackoverflow.com/questions/26650002/angularjs-determine-if-the-view-should-be-displayed-by-an-ajax-call-result-upo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!