Angular 2 route restriction with AngularFire 2 Aut

2019-09-05 16:08发布

问题:

I'm trying to restrict routes to be available only to authenticated users. So far I've added a service call in every route component constructor to check if the user is logged. If not, you get redirected to the login route(index):

logCheck(){
  this.af.auth.subscribe(user => {
    if(!user){
      this.router.navigate(['']);
    }
});

It works. But I'm not sure if using the constructor of each route component for this is the correct way of doing things, because you are actually loading the component before being kicked out. Is there a better way to do it? Like using additional params in the app.routes const maybe?

回答1:

You can use a Guard, that follows the same logic but is instead used with the router, so that when someone tries to access a route, if the service boolean is not set to true, then you get redirected.

Check-out this part of the angular.io router documentation : https://angular.io/docs/ts/latest/guide/router.html#!#guards

There are examples on how to do it, but with what you have already done it should be pretty fast.