问题的原因是因为CanActivate守卫函数必须返回一个布尔对象,以允许或拒绝导航到相应的组件。如果该函数返回false,导航将被取消,并且将停留在当前页面。
下面是解决该问题的示例:
在路由定义中添加CanActivate守卫函数,在该函数中处理认证和授权逻辑,并根据结果返回true或false。
例如:
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (this.authService.isLoggedIn()) {
return true;
}
// 认证失败,重定向到登录页面
this.router.navigate(['/login']);
return false;
}
}
然后在路由定义中使用AuthGuard守卫函数,例如:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
import { AuthGuard } from './auth.guard';
const appRoutes: Routes = [
{ path: '', component: HomeComponent, canActivate: [AuthGuard] },
{ path: 'login', component: LoginComponent }
];
@NgModule({
imports: [RouterModule.forRoot(appRoutes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
这就可以解决CanActivate始终返回false的问题,并在路由守卫函数中处理认证和授权逻辑。