Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了typescript – Angular2 canActivate()调用异步函数大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图使用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不是可观察的

大佬总结

以上是大佬教程为你收集整理的typescript – Angular2 canActivate()调用异步函数全部内容,希望文章能够帮你解决typescript – Angular2 canActivate()调用异步函数所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。