如何检测路由是否返回有效页面?Angular5+localize-router适配需求
解决方案:在Angular 5 + localize-router中处理无语言前缀路径的重定向与404判断
这个场景我之前也遇到过,结合Angular 5和localize-router的特性,咱们可以在NotFoundExceptionComponent里做路由有效性校验,实现智能重定向或404展示,具体方案如下:
核心思路
- 获取当前请求的无语言前缀路径
- 校验该路径在添加默认语言前缀后是否为有效路由
- 有效则重定向到带语言前缀的路径,无效则保持404页面显示
具体实现代码
首先在NotFoundExceptionComponent中注入所需服务,并实现校验逻辑:
import { Component, OnInit } from '@angular/core'; import { Router, Route, UrlSegment } from '@angular/router'; import { LocalizeRouterService } from 'localize-router'; @Component({ selector: 'app-not-found-exception', templateUrl: './not-found-exception.component.html', styleUrls: ['./not-found-exception.component.css'] }) export class NotFoundExceptionComponent implements OnInit { constructor( private router: Router, private localizeRouterService: LocalizeRouterService ) { } ngOnInit(): void { this.handleRouteRedirect(); } private handleRouteRedirect(): void { // 解析当前URL,提取无语言前缀的路径部分 const urlSegments = this.router.parseUrl(this.router.url).root.children['primary'].segments; const currentPathSegments = urlSegments.map(seg => seg.path); const supportedLangs = this.localizeRouterService.parser.locales; // 先判断当前路径是否已包含语言前缀(避免循环重定向) const hasValidLangPrefix = supportedLangs.includes(currentPathSegments[0]); if (hasValidLangPrefix) { // 已有语言前缀但仍匹配404,直接显示404 return; } // 构造带默认语言前缀的路径 const defaultLang = this.localizeRouterService.parser.defaultLang; const pathWithLang = [defaultLang, ...currentPathSegments].join('/'); // 校验该路径是否为有效路由 if (this.isValidRoute(pathWithLang)) { // 重定向到带语言前缀的有效路径 this.router.navigateByUrl(`/${pathWithLang}`); } else { // 无效路径,保持显示404页面 console.log('Invalid path, displaying 404 page'); } } private isValidRoute(targetPath: string): boolean { // 递归遍历路由配置,检查是否存在匹配的有效路由 const checkRoutes = (routes: Route[], path: string): boolean => { for (const route of routes) { // 匹配精确路径,排除通配符路由 if (route.path === path && route.path !== '**') { return true; } // 检查子路由 if (route.children && route.children.length > 0) { const childMatch = checkRoutes(route.children, path); if (childMatch) return true; } } return false; }; return checkRoutes(this.router.config, targetPath); } }
关键注意事项
- 路由配置顺序:确保通配符路由
{ path: '**', component: NotFoundExceptionComponent }放在所有路由的最后,避免拦截有效路由。 - 懒加载路由处理:如果项目使用懒加载模块,
router.config中不会直接包含懒加载的路由规则。此时可以调整校验逻辑,利用router.navigate的错误回调来判断:// 替换isValidRoute的判断逻辑 this.router.navigateByUrl(`/${pathWithLang}`).catch(() => { // 导航失败说明路径无效,显示404 console.log('Invalid path, displaying 404'); }); - localize-router配置:确保
LocalizeRouterModule已正确初始化,默认语言和支持语言列表配置正确。
内容的提问来源于stack exchange,提问作者kris_IV
相关产品推荐
相关产品推荐

