【问题标题】:Handle typos in manual navigation to URLs in Angular处理手动导航到 Angular 中的 URL 中的拼写错误
【发布时间】:2021-10-06 12:25:28
【问题描述】:
正在寻找以下问题的解决方案:
当用户手动导航到一个 url,例如 www.website.com/logi 并打错字时,
我想有一些逻辑将他导航到正确的.../login url。我的网站有大约 10 个具有不同导航 url 的页面,我也想检查那里的拼写错误。逻辑可以检查 1-2 个字符的差异,即使用户打错字也能巧妙地导航。
什么是解决这个问题的好方法?
【问题讨论】:
标签:
angular
typescript
routes
navigation
【解决方案2】:
在所有其他路线之后添加一条包罗万象的路线。在其中,检查您是否应该重定向。如果没有,则显示 404 Not Found 错误。
// Routing module
const routes = [
// Other routes first
{ path: '**', component: NotFoundComponent }
];
// NotFoundComponent
constructor(private route:ActivatedRoute, private router:Router) { }
ngOnInit(): void {
const redirects: [string, string[]][] = [
['logi', ['/login']]
];
for (const redirect of redirects) {
if (
new RegExp(redirect[0], 'i').test(
this.route.snapshot.url[0]?.path || ''
)
) {
// If on Universal server, set Response status to 301
this.router.navigate(redirect[1]);
return;
}
}
// Show 404 error
// If on Universal server, set Response status to 404
}