Angular 2 route restriction with AngularFire 2 Auth

♀尐吖头ヾ 提交于 2019-12-12 05:17:48

问题


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.



来源:https://stackoverflow.com/questions/39183404/angular-2-route-restriction-with-angularfire-2-auth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!