Home > Back-end >  Where to configure the wildcard when I have several modules each with its own routing module?
Where to configure the wildcard when I have several modules each with its own routing module?

Time:03-07

I am doing a test project in Angular that has the following structure:

  • Error (error.component.ts)
  • Home (home.module.ts, home.component.ts y home-routing.module.ts)
  • Hello (hello.module.ts, hello.component.ts y hello-routing.module.ts)

app-routing.module.ts has this:

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

home-routing.module.ts has this:

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

hello-routing.module.ts has this:

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

app.component.ts has this code to navigate to those components:

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

And finally, app.module.ts has this:

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 { }

So far everything is working correctly. The problem is that I don't know where to put the wildcard for paths that doesn't exist. If I put in the app-routing.module.ts the following code:

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

It doesn't matter which route I put. They all take me to the error page. But I only want to take me there when none of this modules are able to solve their respective routes.

How I configure that?

CodePudding user response:

You have to change your routing files:


in app.routing.ts:

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

in home.routing.ts:

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

in hello.routing.ts:

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

CodePudding user response:

Just put it like this

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

Make sure the wildcard is at the very end of routes.

  • Related