Redirect to login route if the user not logged in Angular2 2.0.0-rc.4

六月ゝ 毕业季﹏ 提交于 2019-12-01 07:41:43
Akshay Rao

1.store the user in local storage or cookie and you can check if the user is logged in from there on ngoninit of your component.. on basis of this you can redirect to login page if user is not logged in.

2.you can make a variable in service to be true if user is logged in and on basis of this u can redirect to login page .

i hope this is what u are searching for :)

YOUR ANSWER :-

You can use a canActivate and canDeactivate property in your routes.. first of all set a variable named isLoggedIn as false and make it true on login and u can restrict the user by this by adding canActivate method as :-

in your routes file third property :..

canActivate:[Authentication]

and import authentication from another file .....

import { CanActivate, Router } from '@angular/router';

export class Authentication implements CanActivate {

constructor(private service: Service, private router: Router) {}


canActivate() {

    if (this.authService.isLoggedIn) { return true; }
    this.router.navigate(['/login']);
    return false;
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!