-->

angular2 route for notFound page

2020-07-29 00:58发布

问题:

I try to use children routs. My main routing-module(in root directory):

import { NgModule }             from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ProfileComponent } from './profile/profile.component';
import { NotFoundComponent } from './notfound/notfound.component';
import { LoggedInGuard } from './login-guard/login-guard.component';

const routes: Routes = [
    {path: '', redirectTo: 'home', pathMatch: 'full'},
    {path: 'home', component: HomeComponent, pathMatch: 'full'},
    {path: 'profile', component: ProfileComponent, canActivate: [LoggedInGuard], canLoad: [LoggedInGuard]},
    {path: '**', component: NotFoundComponent},
];
@NgModule({
    imports: [ RouterModule.forRoot(routes) ],
    exports: [ RouterModule ]
})
export class AppRoutingModule {}

and child routing-module(in sub-directory):

import { NgModule }     from '@angular/core';
import { RouterModule } from '@angular/router';

import { PPComponent } from './pp.component';
import { MembersComponent } from './members/members.component';
import { HistoryComponent } from './history/history.component';


@NgModule({
  imports: [
    RouterModule.forChild([
      {
        path: 'partner-program',
        component: PPComponent,
        children: [
          {
            path: '',
            redirectTo: 'members',
            pathMatch: 'full'
          },
          {
            path: 'members',
            component: MembersComponent,
          },
          {
            path: 'history',
            component: HistoryComponent,
          },
        ]
      },


    ])
  ],
  exports: [
    RouterModule
  ]
})
export class PPRoutingModule { }

I have a question about this route {path: '**', component: NotFoundComponent}. Angular2 sees this route before any children routes. And as a result url 'http://localhost:3000/partner-program' shows notFound component. If I remove notFound route, 'http://localhost:3000/partner-program' works fine. How can I declare notFound route and say Angular2 check it in last turn(after child routes)?

Günter Zöchbauer, do you mean smth like this?

RouterModule.forChild([
      {
        path: '',
        children: [
          {
            path: 'partner-program',
            component: PPComponent,
            children: [
              {
                path: '',
                redirectTo: 'members',
                pathMatch: 'full'
              },
              {
                path: 'members',
                component: MembersComponent,
              },
              {
                path: 'history',
                component: HistoryComponent,
              },
            ]
          }
        ]
      }
    ])

回答1:

When you import these modules into the main module please make sure that AppRoutingModule is added on the end. It's all about the order of routes registration