AngularJS: How to hide the template content until user is authenticated?

喜夏-厌秋 提交于 2019-12-06 07:34:50

Well, I don't serve the template (in your case main.html) until the user is authenticated. I have a customized function on server for serving templates, which checks if the user is authenticated. If in the function I find out the user is not logged in, it returns response with 401 status code. In angular code I then hold the request until the authentication and then ask for the template again.

I was inspired to do this by this post: http://www.espeo.pl/2012/02/26/authentication-in-angularjs-application

My solution to the same requirement was to define the following watch:

$rootScope.$watch(
    function() {
        return $location.path();
    },
    function(newValue, oldValue) {  
        if (newValue != '/login' && user is not logged in) {
            $location.path('/login');  
        }
    },
    true);

in a controller associated with the body element of the index page (i. e. the page containing the ng-view directive).

One option is to hide the normal DOM and show an "Authenticating..." message, maybe with a spinner, to give the user some idea of why he/she is sitting there waiting for something to happen. In main.html, include something like:

<spinner ng-hide="appService.wrapper.user"></spinner>
<!-- everything else ng-show="appService.wrapper.user" -->

where <spinner></spinner> is an Angular directive that is replaced by your custom "Authenticating..." message, and user is a variable your appService makes available to MainController. Note that you may need to wrap user in an object within appService, like so:

.service('appService', function() {

  var wrapper = {
    user: null
  };

  function authenticate() {
    // start the authentication and return the promise,
    // but modify wrapper.user instead of user
  }

  return wrapper;

});

You'll also need to store either appService or appService.wrapper in the $scope variable of your MainController.

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