angular - Angular 路由器通配符 URL 不适用于空路径
问题描述
我使用本指南https://github.com/mathisGarberg/angular-folder-structure定义了 APP 结构,并在我的主路由器文件中执行以下操作:
const routes: Routes = [
{
path: '',
component: ContentLayoutComponent,
children: [
...CustomerRouting
],
pathMatch: 'full'
},
{ path: 'app', redirectTo: '', pathMatch: 'full' },
{ path: '**', redirectTo: '', canActivate: [LegacyRedirectGuard]}
];
export const AppRoutingModule = RouterModule.forRoot(routes, {
scrollPositionRestoration: 'enabled',
relativeLinkResolution: 'legacy'
});
我期待当我访问未知 url 时,通配符路由调用LegacyRedirectGuard
将我们重定向到外部网站或 404 页面。但这永远不会发生,因为path: ''
抓住了一切。
CustomerRouting
只是一个嵌套的路由列表。
解决方案
我不确定你的RedirectGard
样子,但这就是我将如何实现它:
重定向保护 TS
import {Injectable} from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, Router, RouterStateSnapshot} from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class RedirectGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
window.location.href = 'https://yourlink.com' + state.url;
return true;
}
}
确保在 app.module 中导入它:
providers: [RedirectGuard]
路由.ts
const routes: Routes = [
{
path: '',
component: ContentLayoutComponent,
children: [
...CustomerRouting
],
pathMatch: 'full'
},
{ path: 'app', redirectTo: '', pathMatch: 'full' },
{ path: '**', component: RedirectGuard, canActivate: [RedirectGuard]}
];
推荐阅读
- asp.net-core - 启动后更新 OpenId/SAML2 (WsFederation)
- arrays - BigQuery - 按数组分组
- angular - 如何在角度中使用带有 pug mixin 的变量?
- unity3d - 如何从 2D 图像创建网格渲染
- javascript - 当我在服务器中将 Promise 与 dialogflow 库一起使用时 - 得到错误
- c - C:自动存储类的数组?
- masstransit - MassTransit 是否有 IPC 传输?
- java - 返回布尔值
- bootstrap-4 - Bootstrap 徽标与移动设备上的导航栏不对齐
- cucumberjs - 将数据从一个步骤同步传递到下一个步骤