typescript – Angular2 canActivate()调用异步函数
发布时间:2020-12-17 07:43:37 所属栏目:安全 来源:网络整理
导读:我试图使用Angular2路由器守卫来限制对我应用程序中某些页面的访问.我正在使用Firebase认证.为了检查用户是否使用Firebase登录,我必须使用回调函来调用FirebaseAuth对象上的.subscribe().这是守卫的代码: import { CanActivate,Router,ActivatedRouteSnapsh
我试图使用Angular2路由器守卫来限制对我应用程序中某些页面的访问.我正在使用Firebase认证.为了检查用户是否使用Firebase登录,我必须使用回调函来调用FirebaseAuth对象上的.subscribe().这是守卫的代码:
import { CanActivate,Router,ActivatedRouteSnapshot,RouterStateSnapshot } from '@angular/router'; import { AngularFireAuth } from "angularfire2/angularfire2"; import { Injectable } from "@angular/core"; import { Observable } from "rxjs/Rx"; @Injectable() export class AuthGuard implements CanActivate { constructor(private auth: AngularFireAuth,private router: Router) {} canActivate(route:ActivatedRouteSnapshot,state:RouterStateSnapshot):Observable<boolean>|boolean { this.auth.subscribe((auth) => { if (auth) { console.log('authenticated'); return true; } console.log('not authenticated'); this.router.navigateByUrl('/login'); return false; }); } } 当导航到具有防护的页面时,经过身份验证或未经过身份验证的页面将打印到控制台(等待响应从Firebase发出一些延迟之后).但是,导航从未完成.另外,如果我没有登录,我被重定向到/ login路由.所以,我遇到的问题是返回true不会向用户显示所请求的页面.我假设这是因为我使用回调,但是我无法弄清楚如何做到这一点.有什么想法吗?
canActivate需要返回一个Observable完成:
@Injectable() export class AuthGuard implements CanActivate { constructor(private auth: AngularFireAuth,state:RouterStateSnapshot):Observable<boolean>|boolean { return this.auth.map((auth) => { if (auth) { console.log('authenticated'); return true; } console.log('not authenticated'); this.router.navigateByUrl('/login'); return false; }).first(); // this might not be necessary - ensure `first` is imported if you use it } } 有一个返回缺失,我使用map()而不是subscribe(),因为subscribe()返回一个Subscription不是可观察的 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |