角通配符路由:“找不到页面”也出现在localhost:4200上

时间:2019-03-11 06:32:49

标签: angular angular6 angular-routing angular-router

“找不到页面”也出现在localhost:4200上。但是部门列表和员工列表工作正常。如何从主页中删除“找不到页面”?

app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { DepartmentListComponent } from './department-list/department- 
list.component';
import { EmployeeListComponent } from './employee-list/employee- 
list.component';
import { PageNotFoundComponent } from './page-not-found/page-not- 
found.component';

const routes: Routes = [
{ path: 'departments', component: DepartmentListComponent},
{ path: 'employee', component: EmployeeListComponent},
{ path: "**", component: PageNotFoundComponent}
];

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

export const rountingComponent = [DepartmentListComponent, 
EmployeeListComponent, PageNotFoundComponent]

app.module.ts

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

import { AppComponent } from './app.component';
import { AppRoutingModule, rountingComponent } from './app-routing.module';

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

app.component.html

<div style="text-align:center">
  <h1>
    Routing and Navigation
  </h1>
</div>
<nav>
  <a routerLink="/departments" routerLinkActive="active">Departments</a>
  <a routerLink="/employee" routerLinkActive="active">Employees</a>
</nav>
<router-outlet></router-outlet>

localhost:4200应该重定向到显示“路由和导航”和两个按钮的app.component.html。

3 个答案:

答案 0 :(得分:0)

您还必须定义本地路线:

{ path: 'departments', component: DepartmentListComponent},
{ path: 'employee', component: EmployeeListComponent},
{ path: '', component: HomeComponent},
{ path: "**", component: PageNotFoundComponent}

答案 1 :(得分:0)

我认为问题在于路由器的插座中没有任何显示。如注释中所指定,您必须在路线中定义一条路线。如果Angular无法找到指定的路径,则会收到404错误。您可以在下面添加路由以重定向到现有路由。

const routes: Routes = [
{ path: 'departments', component: DepartmentListComponent},
{ path: 'employee', component: EmployeeListComponent},
{ path: '', redirectTo: '/departments', pathMatch: 'full'}
{ path: "**", component: PageNotFoundComponent}
];

希望这会有所帮助。

答案 2 :(得分:0)

您应将404重定向放置在路由器config/routes阵列的底部,如下所示:

export const routerConfig: Route[] = [
  {
    path: "",
    component: HomeComponent,
  },
    ////////////////////// Your all other routes here /////////////////////
  { 
    path: "404", 
    component: PageNotFoundComponent 
  }
]