Redirect index page if user is logged in AngularJS

你离开我真会死。 提交于 2019-12-02 17:36:39
Jigar Patel

Make sure to read comment under the answer. When I answered this question I didn't thought about unit tests and design. I was just demonstrating that what can be one of many ways to achieve the desired result

I think the best way to do it under controller or your app.config.run. In your case you should create another module to check for user login status. Inject user login status checking module to your app module.

Here is the link to the sample followed by the app.js code

http://plnkr.co/edit/dCdCEgLjLeGf82o1MttS

var login = angular.module('myLoginCheck', [])
  .factory('$logincheck', function () {
    return function (userid) {
      // Perform logical user logging. Check either 
      // by looking at cookies or make a call to server.
      if (userid > 0) return true;
      return false;
    };
  });

var app = angular.module('myApp', ['myLoginCheck']);

app.config(function ($routeProvider, $locationProvider) {
    $routeProvider
      .when('/publicurl', {})
      .when('/loginurl', {})
      .when('/unauthorize', {})
      .otherwise({redirectTo: '/'});
  })
  .run(function ($logincheck, $location) {
    //console.log("Into run mode");
    console.log("Userid 5 is logged in: ", $logincheck(5));
    console.log("Userid 0  logged in: ", $logincheck(0));

    //now redirect to appropriate path based on login status
    if ($logincheck(0)) {
      //$location.path('/loginurl'); or          
    }
    else {
      //$location.path('/publicurl'); or 
    }
  });

app.controller('MainCtrl', function ($scope) {
  $scope.name = 'World';
});

I just did this, by making a dummy template and small controller for the / path which redirects as appropriate.

controllers.controller('loginController',
                       ['$scope', '$location', '$cookies',
                        function($scope, $location, $cookies) {
    if (!!$cookies.user) {
        console.log("already logged in!");
        $location.path('/shows');
    } else {
        console.log("need to login!");
        $location.path('/users');
    }
}]);

var app = angular.module('app', ['ngRoute', 'ngCookies', 'controllers', 'services']);

app.config(['$routeProvider',
            function($routeProvider) {
    $routeProvider.when('/users', {
        templateUrl: "partial/users.html",
        controller: 'userController'
    });
    $routeProvider.when('/shows', {
        templateUrl: "partial/shows.html",
        controller: 'showController'
    });
    $routeProvider.when('/', {
        template: '',
        controller: 'loginController'
    });
    $routeProvider.otherwise({
        redirectTo: '/'
    });
}]);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!