首页 > 解决方案 > 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只是一个嵌套的路由列表。

标签: angularangular-routing

解决方案


我不确定你的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]}
];

推荐阅读