[英]Angular routerLink and Router.Navigate behaving differently
我在應用程序路由模塊中具有以下代碼。
const routes: Routes = [
{ path: '', redirectTo:'Person/AllPersons', pathMatch:'full' },
{ path: 'Person/AllPersons', component: AllPersonsComponent },
{ path: 'Person/AddPerson', component: AddPersonComponent },
{ path: 'Teacher/AllTeachers', component: AllTeachersComponent },
{ path: 'Teacher/AddTeacher', component: AddTeacherComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
現在在AllPersonsComponent.html中,我有以下代碼。
<a routerLink="Teacher/AddTeacher">Add Teacher</a>
現在,當我單擊它時。 它沒有重定向到AddTeacher組件。 而是按如下方式填充錯誤。無法匹配任何路由。 網址段:“人員/所有人員/老師/添加老師”。
但是,當我這樣做時,它會重定向到正確路徑。
<a (click)="Func()">Add Teacher</a>
並在.ts文件中如下所示。
Func() {
this.router.navigate(['Teacher/AddTeacher']);
}
然后,它導航到“添加教師”組件。 關於routerLink為何失敗以及如何通過routerLink發生故障,有人可以幫助我嗎?
您的routerLink應該以正斜杠開頭(添加老師)
根據角度文件
如果第一段以/開頭,則路由器將從應用程序的根目錄查找路由。
因此,如果您在開頭添加(/),則您的鏈接將以-domain / Teacher / AddTeacher開頭后呈現
嘗試這個?
<a [routerLink]="['/Teacher/AddTeacher']">Add Teacher</a>
我發現您首先以錯誤的方式聲明了路線,您應該為Person
和Teacher
設置2條分離的路線,而與Person
或Teacher
相關的其他路線應該為子路線,並且在這里還有一個錯誤,您應該將所有路線都聲明為小寫,因此解決問題的方法應如下所示:
const routes: Routes = [
{ path: '', redirectTo:'person/all-person', pathMatch:'full' },
{ path: 'person', component: PersonComponent,
children: [
{ path: '', redirectTo: 'overview', pathMatch: 'full' },
{ path: 'all-persons', component: AllPersonComponent},
{ path: 'add-person', component: AddPersonComponent}
]
},
{ path: 'teacher', component: PersonComponent,
children: [
{ path: '', redirectTo: 'overview', pathMatch: 'full' },
{ path: 'all-teachers', component: AllTeacherComponent},
{ path: 'add-teacher', component: AddTeacherComponent}
]
},
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
或者,您可以使用簡單的路線person
和person/:page-type
並且可以使用一個組件,並且在ngOnInit
可以使用類似的方法
showAllPersonTemplate = false;
showAddPersonTemplate = false;
ngOnInit(){
const pageType = this.router.params
let pageType = this.route.snapshot.paramMap.get('page-type');
// and here you verify what route user navigate
if(pageType === 'add-person' ) {
this.showAddPersonTemplate = true;
}
if(pageType === 'all-person' ) {
this.showAllPersonTemplate = true;
}
// And based on routes params you show or hide different html
}
閱讀有關角度文檔的更多信息https://angular.io/guide/router
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.