当我有多个模块,每个模块都有自己的路由模块时,在哪里配置通配符?

问题描述 投票:0回答:3

我正在 Angular 中做一个测试项目,其结构如下:

  • 错误(error.component.ts)
  • Home(home.module.ts、home.component.ts 和 home-routing.module.ts)
  • 你好(hello.module.ts,hello.component.ts y hello-routing.module.ts)

app-routing.module.ts 有这个:

const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
];

home-routing.module.ts 有这个:

const routes: Routes = [
  { path: 'home', component: HomeComponent },
];

hello-routing.module.ts 有这个:

const routes: Routes = [
  { path: 'hello', component: HelloComponent }
];

app.component.ts 有此代码可导航到这些组件:

<nav>
  <a routerLink="/home" routerLinkActive="linkActive">Home</a>
  <a routerLink="/hello" routerLinkActive="linkActive">Say hello</a>
</nav>
<router-outlet></router-outlet>

最后,app.module.ts 有这个:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeModule } from './home/home.module';
import { HelloModule } from './Hello/Hello.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HomeModule,
    HelloModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

到目前为止一切正常。 问题是我不知道在哪里放置不存在的路径的通配符。如果我在 app-routing.module.ts 中放入以下代码:

{ path: '**', component: ErrorComponent }

我选择哪条路线并不重要。他们都带我到错误页面。但我只想在这些模块都无法解决各自的路线时带我去那里。

我该如何配置?

angular routes wildcard
3个回答
0
投票

您必须更改路由文件:


在 app.routing.ts 中:

const routes: Routes = [
  { path: 'hello', component: HelloComponent}, 
  { path: 'home', component: HomeComponent },
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: '**', component: ErrorComponent }
]

在 home.routing.ts 中:

const routes: Routes = [
{ path: '', component: HomeComponent },
];

在 hello.routing.ts 中:

const routes: Routes = [
{ path: '', component: HelloComponent }
];

0
投票

来自不同路由模块的路由数组将按照相关路由模块导入的顺序连接起来。因此,如果 AppRoutingModule 包含通配符路由,则 AppRoutingModule 是最后导入的模块非常重要。

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HomeModule,
    HelloModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

0
投票

在构建 Angular 应用程序的路由时,仔细安排路由导入和模块配置的顺序至关重要。当您使用通配符路由(捕获所有不匹配路径的路由)时,这一点尤其重要。为了确保功能正常,建议导入包含通配符路由的模块作为最终导入。这可确保维持预期的行为。

© www.soinside.com 2019 - 2024. All rights reserved.