Angular Guard失效

问题描述 投票:1回答:1

我希望我的身份验证防护基于定期触发布尔值的可观察对象来允许/限制访问。我的想法是:

auth$ = interval(5000).pipe(map((n) => n % 2 === 0));

canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean {
    return this.auth$;
}

[当触发器从false变为true时有效,但反之则相反,看起来防护装置不再处于活动状态。

angular typescript guard auth-guard
1个回答
0
投票

每次导航开始都会触发一次警卫。

一旦角钢从其后卫退订了它的第一个发射物,并使用发射的值来允许/禁止布线。

这意味着-您不能定期发出保护值来更改原始发出的值。

您要实现的目标可以通过以下方式实现:

import {Injectable, OnDestroy} from '@angular/core';
import {CanActivate} from '@angular/router';
import {interval, Observable, Subject} from 'rxjs';
import {map, takeUntil, tap} from 'rxjs/operators';

@Injectable({
    providedIn: 'root',
})
export class AuthGuard implements CanActivate, OnDestroy {
    protected readonly auth$: Subject<boolean> = new Subject();
    protected readonly destroy$: Subject<void> = new Subject();

    constructor(
    ) {
        interval(5000).pipe(
            map(n => n % 2 === 0),
            tap(value => this.auth$.next(value)),
            takeUntil(this.destroy$),
        ).subscribe();
    }

    public canActivate(): Observable<boolean> {
        return this.auth$;
    }

    public ngOnDestroy(): void {
        this.destroy$.next();
        this.destroy$.complete();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.