use*_*308 3 redirect routes canactivate angular angular-activatedroute
我有一个routes.ts像下面这样的文件:
import { AuthGuardService as AuthGuard } from '../services/auth-guard.service';
export const routes:Routes = [
{path : '' , redirectTo : '/home' , pathMatch : 'full'},
{path: 'home' , component : HomeComponent},
{path: 'users' , component : UsersComponent, canActivate: [AuthGuard]},
];
Run Code Online (Sandbox Code Playgroud)
和这样的auth-guard.service.ts文件:
export class AuthGuardService implements CanActivate {
constructor(public auth: AuthService, public router: Router) {}
canActivate(): boolean {
if (!this.auth.isLoggedIn()) {
this.router.navigate(['home']);
return false;
}
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
它适用于已知路线,例如users但是当我尝试未知路线时,homeee它无法正常工作并显示带有页眉和页脚且其中没有内容的页面。如何将所有未知路由重定向到 home 组件?
我也想知道这是否是我喜欢做的事情的好方法?(我喜欢只有登录用户才能看到除 home 组件之外的其他组件,并且登录前的所有路由都被重定向到 home 组件)。
Angular 文档建议定义通配符路由。
添加通配符路由来拦截无效的 URL 并优雅地处理它们。通配符路由的路径由两个星号组成。它匹配每个 URL。如果它无法匹配配置中较早的路由,则路由器将选择此路由。通配符路由可以导航到自定义的“404 Not Found”组件或重定向到现有的
路由器选择具有第一个匹配获胜策略的路由。通配符路由是路由配置中最不具体的路由。确保它是配置中的最后一条路由。
在你的情况下:
{ path: '**', redirectTo: 'home'}
Run Code Online (Sandbox Code Playgroud)
通过添加后备路由来增强现有的路由数组:
export const routes:Routes = [
{path : '' , redirectTo : '/home' , pathMatch : 'full'},
{path: 'home' , component : HomeComponent},
{path: 'users' , component : UsersComponent, canActivate: [AuthGuard]},
{path: '**' , component : HomeComponent},
];
Run Code Online (Sandbox Code Playgroud)
请小心将其包含在数组的末尾,否则它将捕获所有路由。