【问题标题】:Angular Guard InvalidationAngular Guard 失效
【发布时间】:2020-05-09 11:06:11
【问题描述】:
我希望我的身份验证守卫根据定期触发布尔值的 observable 来允许/限制访问。我的想法是:
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】:
每次导航开始时都会触发一次守卫。
一旦 Angular 从守卫那里得到第一次发射,它就会取消订阅并使用发射的值来允许/禁止路由。
这意味着 - 您不能定期发出值来更改最初发出的值。
您想要实现的目标可以通过以下方式实现:
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();
}
}