我今天需要路由方面的帮助。我有一组组件,每个组件都有不同的路径。我想为父级和子级中的通配符路由添加"PageNotFoundComponent"。我的意思是,这是我的网址:
http://localhost:8888/programs/cohorts
CCD_ 2是CCD_。当programs
或cohorts
错误时,我想重定向到PageNotFoundComponent
。这是我的代码:
应用程序路由模块.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
}
])
],
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 { }
Urlhttp://localhost:8888/programs/cooohrt
与programs/:dashboardId
匹配
因此,空白屏幕很可能是DashboardComponent
的结果
如果您想将id与有效对象匹配,可以使用RouteGuard或者当你意识到对象不存在时,简单地从你的组件重定向
this.router.navigate(['404-not-found'], { skipLocationChange });
skipLocationChange用于保持原始(错误(url对用户可见。'404未找到"只是任何与任何url不匹配的东西(正确匹配您的通配符url(