0

我今天需要路由方面的帮助。我有一组组件,每个组件都有不同的路线。我想在父级和子级中为通配符路由添加“PageNotFoundComponent”。我的意思是,这是我的网址:

http://localhost:8888/programs/cohorts

cohorts是 的孩子programs。我想重定向到PageNotFoundComponent任何一个programscohorts错误的时候。这是我的代码:

应用程序路由.module.ts

...
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';

const routes: Routes = [
    { path: 'login', component: LoginComponent },
    {
        path: '',
        component: ProgramsComponent,
        canActivate: [AuthGuard]
        children: [
            {
                path: 'programs/:dashboardId',
                component: DashboardComponent
            },
            {
                path: 'programs/:dashboardId/:subPageId',
                component: DashboardComponent
            },
            {
                path: 'programs/**',
                component: PageNotFoundComponent 
            }
        ]
    },
    { path: '**', component: PageNotFoundComponent }
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule],
    providers: [DashboardModelResolver, DashboardListResolver]
})
export class AppRoutingModule {}

我在某个地方犯了错误。请指出并帮助我。

这工作得很好:http://localhost:8888/prrrooogrm/cohorts

但这是给空白屏幕:http://localhost:8888/programs/cooohrt

我也试过这个:

imports: [
    RouterModule.forRoot(routes),
    RouterModule.forChild([
        {
            path: '**',
            component: PageNotFoundComponent
        }
    ])
],
4

2 回答 2

0
const routes: Routes = [
  {
    path: '',
    component: HomeComponent,
    pathMatch: 'full'
  },
  {
    path: 'not-found',
    component: NotFoundComponent,
    pathMatch: 'full'
  },
  {
    path: '**',
    redirectTo: 'not-found',
    pathMatch: 'full'
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
于 2021-07-20T11:08:56.227 回答
0

网址http://localhost:8888/programs/cooohrt匹配于programs/:dashboardId

所以空白屏幕可能是DashboardComponent

如果您想将 id 匹配到有效对象,您可以使用 RouteGuard 或在您意识到该对象不存在时简单地从您的组件重定向

this.router.navigate(['404-not-found'], { skipLocationChange });

skipLocationChange 是为了保持原始(错误)url 对用户可见。'404-not-found' 只是任何 url 都不匹配的东西(与通配符 url 正确匹配)

于 2021-07-20T11:07:30.030 回答