在Angular 8中,要实现路由不重定向到路由,可以使用CanActivate
守卫来控制路由的访问权限。下面是一个示例解决方法:
AuthGuard
守卫类,实现CanActivate
接口。该类将控制路由的访问权限。import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router) { }
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
// 在这里添加你的逻辑代码,来判断用户是否有权限访问该路由
// 如果用户有权限访问该路由,返回true
return true;
// 如果用户没有权限访问该路由,可以进行重定向到其他路由
// this.router.navigate(['/other-route']);
// 返回false来阻止用户访问该路由
// return false;
}
}
canActivate
属性指定要使用的守卫类。import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
import { AuthGuard } from './auth.guard';
const routes: Routes = [
{ path: '', component: HomeComponent, canActivate: [AuthGuard] },
{ path: 'login', component: LoginComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
在上面的示例中,AuthGuard
守卫类被指定为根路径的守卫,即HomeComponent
组件的访问权限由AuthGuard
控制。
AuthGuard
守卫类的canActivate
方法中添加你的逻辑代码,来判断用户是否有权限访问该路由。如果用户有权限访问该路由,返回true
,否则可以进行重定向到其他路由,并返回false
来阻止用户访问该路由。需要注意的是,AuthGuard
守卫类需要在模块中进行提供,可以在@Injectable
装饰器中使用providedIn: 'root'
来提供该守卫类,也可以在模块的providers
数组中手动提供。