Every time a navigation starts, a guard is activated.
Angular will unsubscribe after receiving the first emit from a guard, using that value to determine whether to allow or prohibit routing.
This means that you cannot emit values periodically in a guard to override the original emitted value.
If you want to achieve this functionality, you can implement it as shown below:
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$;
}
// It's recommended to unsubscribe once the guard is no longer needed
public ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
}