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

后端 未结 1 870
一生所求
一生所求 2021-01-13 23:31

This is my html file


      
      
1条回答
  •  北荒
    北荒 (楼主)
    2021-01-14 00:27

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

    0 讨论(0)
提交回复
热议问题