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

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

问题描述

我正在尝试将路由限制为仅对经过身份验证的用户可用.到目前为止,我已经在每个路由组件构造函数中添加了一个服务调用来检查用户是否已登录.如果没有,您将被重定向到登录路由(索引):

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(['']);
    }
});

它有效.但是我不确定为此使用每个路由组件的构造函数是否是正确的做事方式,因为您实际上是在被踢出之前加载组件.有没有更好的方法来做到这一点?喜欢在 app.routes const 中使用额外的参数吗?

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?

推荐答案

您可以使用 Guard,它遵循相同的逻辑,但与路由器一起使用,以便当有人尝试访问路由时,如果服务布尔值未设置为 true,然后您会被重定向.

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.

查看 angular.io 路由器文档的这一部分:https://angular.io/docs/ts/latest/guide/router.html#!#guards

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天全站免登陆