AngularFire 2 Auth的Angular 2路由限制 [英] Angular 2 route restriction with AngularFire 2 Auth

查看:179
本文介绍了AngularFire 2 Auth的Angular 2路由限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图限制路由只能通过身份验证的用户。到目前为止,我已经在每个路由组件构造函数中添加了一个服务调用来检查用户是否被记录。如果没有,你会被重定向到登录路径(index):

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

有效。但我不确定是否使用每个路由组件的构造函数是正确的做事方式,因为实际上在加载组件之前被踢出。
有没有更好的方法来做到这一点?你可以使用一个Guard,它遵循相同的逻辑,但是它可以是一个或者多个参数,而不是一个参数。而是和路由器一起使用,这样当有人试图访问路由时,如果服务布尔值没有设置为true,那么你会被重定向。 angular.io路由器文档的一部分: https:// angular。 io / docs / ts / latest / guide / router.html#!#警卫



有关如何操作的示例,已经做了它应该是相当快的。


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?

解决方案

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.

这篇关于AngularFire 2 Auth的Angular 2路由限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆