在CanActivateFn中使用@Inject提供路由
例如:
import { Injectable, Inject } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
@Injectable({
providedIn: 'root',
})
export class AuthGuard implements CanActivate {
constructor(private router: Router, @Inject('Router') private appRouter: Router) { }
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (this.isLoggedIn()) {
return true;
} else {
this.appRouter.navigate(['login']);
return false;
}
}
private isLoggedIn(): boolean {
// authentication logic here
}
}
在示例代码中,我们使用了@Inject来提供路由实例,这样就可以在CanActivateFn中正确地访问路由了。