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

查看:99
本文介绍了重定向索引页,如果用户在登录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.

我有一个检查,看看用户是否登录服务(例如,检查饼干)当角服务负载触发。我曾尝试使用$ 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 code

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天全站免登陆