如果用户已登录 AngularJS,则重定向索引页面 [英] Redirect index page if user is logged in AngularJS

查看:36
本文介绍了如果用户已登录 AngularJS,则重定向索引页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试改变用户访问我的网站时看到的页面.如果他们是匿名的,他们应该看到注册页面.如果他们已经登录,他们应该会看到他们的仪表板.

I am trying to vary the page a user sees when they go to my website. If they are anonymous they should see the register page. If they have logged in they should see their dashboard.

我有一项服务,用于检查用户是否已登录(例如检查 cookie),该服务在 Angular 服务加载时触发.我曾尝试使用 $routeProvider 进行重定向,但是在初始化 $routeProvider 时尚未触发该服务,因此它始终认为用户未登录.

I have a service which checks to see if the user is logged in (e.g. check cookies) which triggers when the Angular services load. I have tried to use the $routeProvider to redirect but the service has not been triggered when the $routeProvider is being initialized so it always thinks that the user is not logged in.

一旦加载了初始页面,我就可以轻松重定向,但我正在努力重定向加载的第一个页面.任何人都可以就如何做到这一点提供建议吗?

I can redirect easily once the initial page has been loaded but I am struggling to redirect the first page loaded. Can anyone give advice on how to do this?

推荐答案

请务必阅读答案下方的评论.当我回答这个问题时,我没有考虑单元测试和设计.我只是在证明什么可以成为实现预期结果的多种方法之一

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

我认为在控制器或您的 app.config.run 下执行此操作的最佳方法.在您的情况下,您应该创建另一个模块来检查用户登录状态.将用户登录状态检查模块注入您的应用模块.

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.

这是示例的链接,后跟 app.js 代码

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';
});

这篇关于如果用户已登录 AngularJS,则重定向索引页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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