AuthGuard 路由器角度 [英] AuthGuard router angular

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

问题描述

我正在尝试进行持久登录并且一切正常,除非我从仪表板重新加载页面,该页面是受 AuthGuard 保护的页面,我被重定向到登录页面,但我仍然登录,导航栏也正常工作.任何建议都会对我有很大帮助.

I am trying to make a persistent login and everything works fine except if I am reload the page from the dashboard which is a page protected of AuthGuard I get redirected to login page but still I am logged in and also navbar works properly.Any suggestions would help me out a lot.

export class AuthGuard implements CanActivate {

    constructor(private auth: AuthService, private router: Router) {

    }

    canActivate(
        next: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
        return this.auth.getLoggedIn
            .pipe(
                map((res: boolean) => {
                    console.log(res);  // this one returns false when I reload page    
                    if (!res) {
                        this.router.navigate(['login']);
                        return false;
                    }
                    return true;
                })
            );
    }
}

下面是我的身份验证服务

Below is my auth service

export class AuthService {

    private loggedIn: BehaviorSubject<boolean>;

    constructor(private http: HttpClient) {

        this.loggedIn = new BehaviorSubject<boolean>(false);
    }

    setLoggedIn(value: boolean) {
        this.loggedIn.next(value);
    }

    get getLoggedIn() {
        this.updatelogin().subscribe(res => {
            this.loggedIn.next(res);

        })
        return this.loggedIn.asObservable();
    }

    updatelogin() {
        return this.http.get<boolean>('/api/islogged'); // API server returns a boolean by calling req.isAuthenticated()-passport
    }
}

我删除了不必要的代码,但如果您需要更多信息,请告诉我,我会编辑我的帖子.

I deleted unnecessary code but if you need anything more let me know and I will edit my post.

推荐答案

只需使用 Subject 而不是 BehaviorSubject 就可以解决问题:

Simply using a Subject instead of a BehaviorSubject should resolve the issue :

首先创建一个带有假值的 BehaviorSubject

You start by creating a BehaviorSubject with a false value

this.loggedIn = new BehaviorSubject<boolean>(false);

然后您进行 HTTP 调用以发出新值

Then you make an HTTP call to emit an new value

this.updatelogin().subscribe(res =>{
   this.loggedIn.next(res);
 })

但是你不会等到这个调用结束才返回一个值

But you don't wait for this call to end to return a value

return this.loggedIn.asObservable();

这篇关于AuthGuard 路由器角度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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