我希望我的auth guard允许/限制基于定期触发布尔值的可观察对象的访问。我的想法是:
auth$ = interval(5000).pipe(map((n) => n % 2 === 0));
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean {
return this.auth$;
}当触发器从false转到true时,它是有效的,但不是相反的,看起来守卫不再活动。
发布于 2020-05-09 19:17:17
每次导航开始时都会触发一次防护。
一旦angular从一个守卫那里获得了第一个emit,它就会取消订阅,并使用发出的值来允许/禁止路由。
它的意思是-你不能定期发送保护的值来改变最初发送的值。
你想要实现的目标可以通过下面的方式实现:
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$;
}
// not sure if this part works for guards
// but would be nice to unsubscribe once you don't need this guard
// anymore
public ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
}https://stackoverflow.com/questions/61695722
复制相似问题