[英]Angular 2 routing inside a component not working (this.router.navigate not working)
[英]Angular routing bug - this.router.navigateByUrl() and this.router.navigate()
我正在創建 angular 應用程序,它將以比自述文件更復雜的方式處理我的 GitHub 應用程序的文檔。 我想在單擊 topnav 下拉列表后將用戶重定向到選定的路由,但路由器存在問題。 (我需要使用一些參數進行重定向,但即使使用簡單的路徑編輯器也不起作用)。 這些方法重定向到目標路由大約 1 秒(如例外),然后用戶被重定向回根頁面。
代碼:
/* First element is project name, second is category/part of application name */
choices = ["typing_speed_test", "overview"]
json = json
constructor(private router: Router){}
onProjectClick($event){
this.choices[0] = $event.target.innerHTML.trim();
this.choices[1] = "overview";
this.redirect();
}
onCategoryClick($event){
this.choices[1] = $event.target.innerHTML.trim();
this.redirect();
}
redirect(){
this.router.navigateByUrl("404");
}
路線:
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'project/:project_name/:category', component: SubpageComponent },
{ path: '404', component: NotFoundComponent },
//{ path: '**', redirectTo: '404', pathMatch: 'full' }
];
有問題的 gif 鏈接: https ://imgur.com/a/x2mPxvh github 存儲庫中的完整代碼: https : //github.com/Dolidodzik/DocsForMyApps (如果您使用此處的代碼來回答此問題,請指出你的答案)
我想我可能犯了一些愚蠢的錯誤,因為我對 Angular 還很陌生,但我做不到,因為每個谷歌問題都顯示我解決了錯誤,當重定向根本不起作用時,而不是像我這樣的錯誤情況。
您需要從導航欄中的錨鏈接中刪除href="#"
。 它導致瀏覽器重新加載:
<a class="dropdown-item" *ngFor="let item of categories() | keyvalue">
{{item.key}}
</a>
這也是一個有點奇怪的解決方案:
this.choices[0] = $event.target.innerHTML.trim();
您最好只在模板中的函數調用中發送item
變量,然后您可以在組件事件處理程序中讀取它:
onProjectClick(item){
this.choices[0] = item.key;
this.choices[1] = "overview";
this.redirect();
}
問題是你的 lins 看起來像這樣:
<a href="#" (click)="navigateInsideApp(routeX)">link</a>
默認鏈接行為會導致您的應用從一開始就重新加載。 你應該使用[routerLink]="['someUrl']"
而不是href
。 如果您在某些情況下需要該 href,請考慮調用$event.preventDefault()
取消本機瀏覽器導航
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.