Angular2 canActivate()调用异步函数

编程入门 行业动态 更新时间:2024-10-27 07:22:59
本文介绍了Angular2 canActivate()调用异步函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用Angular2路由器防护来限制对我的应用程序中某些页面的访问.我正在使用Firebase身份验证.为了检查用户是否使用Firebase登录,我必须通过回调在FirebaseAuth对象上调用.subscribe().这是警卫的代码:

I am trying to use Angular2 router guards to restrict access to some pages in my app. I am using Firebase Authentication. In order to check if a user is logged in with Firebase, I have to call .subscribe() on the FirebaseAuth object with a callback. This is the code for the guard:

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; }); } }

当导航到上面有保护层的页面时,将在控制台上打印authenticated或not authenticated(经过一小段等待Firebase的响应之后).但是,导航从未完成.另外,如果我没有登录,我将被重定向到/login路由.因此,我遇到的问题是return true不会向用户显示请求的页面.我假设这是因为我正在使用回调,但是我无法弄清楚该如何做.有什么想法吗?

When a navigate to a page that has the guard on it, either authenticated, or not authenticated is printed to the console (after some delay waiting for the response from firebase). However, the navigation is never completed. Also, if I am not logged in I am redirected to the /login route. So, the issue I am having is return true doesn't display the requested page to the user. I'm assuming this is because I am using a callback, but I am unable to figure out how to do it otherwise. Any thoughts?

推荐答案

canActivate需要返回一个完成的Observable:

canActivate needs to return an Observable that completes:

@Injectable() export class AuthGuard implements CanActivate { constructor(private auth: AngularFireAuth, private router: Router) {} canActivate(route:ActivatedRouteSnapshot, 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 } }

缺少一个return,我使用map()而不是subscribe(),因为subscribe()返回的是Subscription而不是Observable

There is a return missing and I use map() instead of subscribe() because subscribe() returns a Subscription not an Observable

更多推荐

Angular2 canActivate()调用异步函数

本文发布于:2023-11-23 03:56:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1620003.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   canActivate

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!