canActivate 不响应订阅更改 Angular 2 路由器 AngularFire2 [英] canActivate doesn't respond upon subscription change Angular 2 Router AngularFire2

查看:23
本文介绍了canActivate 不响应订阅更改 Angular 2 路由器 AngularFire2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 AngularFire2.我是这样处理我的 AuthGuard 服务的:

I'm using AngularFire2. This is how I approached my AuthGuard service:

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    this.af.auth.subscribe((auth) =>  {
      if(auth == null) {
        this.router.navigate(['/login']);
        this.allowed = false;
      } else {
        this.allowed = true;
      }
    })
    return this.allowed;
  }

上述代码有效,除非我直接访问受保护的页面(我在浏览器中输入 URL),否则在订阅解析为 true 后它不会加载相应的组件.

The above code works, except when I visit a guarded page directly (i enter URL in browser), it doesn't load the respective component after the subscription resolves to true.

在角度 1 中,保护路线是确保在路线加载之前首先解决某些问题.

In angular 1, guarding the route was ensuring something resolves first before the route even loads.

它出现在 angular 2 中,路由加载(无论是真还是假,并且不等待来自线路的任何响应),因此当订阅值返回为真时,我必须转到另一条路由,然后在它起作用之前回来.

It appears in angular 2, the route loads (whether true or false, and doesn't wait for any response from the wire), therefore by the time the subscription value returns as true, I have to go to another route, then come back before it works.

保护我的路线以在 Angular 2 中响应的正确方法是什么?

What is the proper way to guard my route to be responsive in Angular 2?

推荐答案

在你的代码中 return this.allowed; 在传递给 this.af.auth.subscribe 的回调函数之前执行(...) 被执行.

In your code return this.allowed; is executed before the callback function passed to this.af.auth.subscribe(...) is executed.

应该是这样

  import 'rxjs/add/operator/map';
  import 'rxjs/add/operator/first';
  import { Observable } from 'rxjs/Observable';


  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    return this.af.auth.map((auth) =>  {
      if(auth == null) {
        this.router.navigate(['/login']);
        return false;
      } else {
        return true;
      }
    }).first()
  }

这篇关于canActivate 不响应订阅更改 Angular 2 路由器 AngularFire2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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