Angular 5特定页面路由配置:分场景跳转不同404页面
搞定这个差异化404跳转其实不难,Angular 5的路由系统完全能实现,给你两个靠谱的方案,你根据自己的场景选就行:
方案一:利用路由层级+通配符匹配顺序
这是最直接的实现方式,核心是利用Angular路由从上到下匹配的规则,给log-in配置子路由通配符,再在全局配置另一个通配符。
步骤:
- 先确保你已经创建了两个NotFound组件:
NotFound1Component(对应log-in下的无效路径)和NotFound2Component(对应其他无效路径)。 - 在你的路由配置文件里调整路由顺序:
const routes: Routes = [ // 先放所有有效路由(比如你的registration、home这些) { path: 'registration', component: RegistrationComponent }, { path: 'home', component: HomeComponent }, // 给log-in配置带子路由的规则 { path: 'log-in', component: LogInComponent, children: [ // 匹配log-in下所有不存在的子路径,重定向到not-found-1 { path: '**', redirectTo: '/not-found-1' } ] }, // 配置两个404页面的路由 { path: 'not-found-1', component: NotFound1Component }, { path: 'not-found-2', component: NotFound2Component }, // 全局通配符,匹配所有非log-in的无效路径 { path: '**', redirectTo: '/not-found-2' } ];
原理:
- 当用户访问
log-in/3/4这类路径时,Angular会先匹配到log-in的父路由,然后检查它的子路由,**会匹配所有未定义的子路径,直接重定向到not-found-1。 - 当用户访问
registration/3/4这类路径时,Angular找不到对应的有效路由(假设你没给registration配置子路由通配符),就会匹配到最下面的全局**,重定向到not-found-2。
注意:
- 一定要把
log-in的路由放在全局通配符之前,否则全局通配符会先匹配所有路径,导致log-in的子路由规则失效。
方案二:用路由守卫做自定义判断
如果你的路由场景更复杂(比如有很多嵌套路由,或者需要更灵活的路径判断),可以用CanActivate守卫来实现。
步骤:
- 创建一个路由守卫服务:
import { Injectable } from '@angular/core'; import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; @Injectable() export class NotFoundGuard implements CanActivate { constructor(private router: Router) {} canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { const currentUrl = state.url; // 判断当前URL是否是log-in下的无效路径(注意是/log-in/,避免匹配到有效的/log-in) if (currentUrl.startsWith('/log-in/')) { this.router.navigate(['/not-found-1']); } else { this.router.navigate(['/not-found-2']); } return false; // 因为要重定向,所以返回false阻止原路由激活 } }
- 在路由配置里注册守卫,并给全局通配符路由绑定这个守卫:
const routes: Routes = [ // 所有有效路由 { path: 'log-in', component: LogInComponent }, { path: 'registration', component: RegistrationComponent }, { path: 'home', component: HomeComponent }, // 404页面路由 { path: 'not-found-1', component: NotFound1Component }, { path: 'not-found-2', component: NotFound2Component }, // 全局通配符路由,用守卫判断跳转方向 { path: '**', canActivate: [NotFoundGuard] } ];
- 别忘了在你的NgModule里注册这个守卫:
@NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], providers: [NotFoundGuard] // 注册守卫 }) export class AppRoutingModule { }
原理:
当用户访问任何无效URL时,全局通配符路由会触发NotFoundGuard,守卫会检查当前URL的前缀,如果是/log-in/开头的无效路径,就跳转到not-found-1,否则跳not-found-2。
注意:
- 如果
log-in本身有有效的子路由(比如log-in/profile),你需要在守卫里排除这些有效路径,避免误跳转。比如可以加个判断:if (currentUrl.startsWith('/log-in/') && !currentUrl.includes('/log-in/profile'))。
内容的提问来源于stack exchange,提问作者levi
相关产品推荐
相关产品推荐

