2017-09-13 168 views
4

在Angular 4中有一些基本的路由概念,我不明白。角4:路由到路由不起作用

的index.html

<base href="/"> 

文件結構:

- app 
|- app.routings.ts 
|- collections 
|-- collection.component.ts 
|-- collection.component.html 
|-- collectioninfo.component.ts 
|-- collectioninfo.component.html 
|- shared 
|-- header.component.html 
|-- header.component.ts 

我在header.component.html鏈接:如果我

<a class="nav-link" [routerLink]="['/collections']"> 
    Collections 
</a> 

點擊它我登陸localhost:4200 /集。當點擊一個按鈕,該URL以編程方式改變(collection.component.ts):

this.router.navigate(['/collections/', collection.name]); 

我結束了在localhost:4200 /收藏/名稱 - 無一不精。現在我編程地想要回到/ collections(在collectioninfo.component.ts中):

this.router.navigate(['/collections']); 

但是,這並不起作用。 URL不會改變,我得到一個錯誤,說一個參數無法加載 - 顯然/集合/名稱再次加載。認爲這可能是一個路徑問題,但這樣的事情也不起作用:

this.router.navigate(['../collections']); 

附加信息:當我手動刷新頁面,同時上/收藏我被轉發到主頁再次,但我認爲這是另一個問題,與此行爲無關。

app.routing.ts

const APP_ROUTES: Routes = [ 
    ... 
    { path: 'collections', component: CollectionComponent }, 
    { path: 'collections/:id', component: CollectionInfo }, 
]; 
+0

您是否嘗試過'navigateByUrl'而不是'navigate',我不知道它是否會解決您的問題,但我使用它來編程頁面更改 – Surreal

+1

感謝您的提示,不幸的是,這也不起作用一些行爲)。 – user3255061

+0

您的空路徑是如何定義的以及在您的頭文件中是什麼? – JayDeeEss

回答

1

原來我的firebase代碼搞砸了 - 它試圖在轉到另一條路由之前重新加載頁面。這導致了一個錯誤,因爲從前面的路線移交的一些參數丟失了。

export const routing = RouterModule.forRoot(APP_ROUTES, { enableTracing: true }) 

在app.routing.ts中對調試非常有用。

2

在你的相對路徑this.router.navigate(['../collections']);您要瀏覽到localhost:4200/collections/collections。嘗試this.router.navigate(['../']);

如果這不起作用,還供應ActivatedRoute作爲對於relativeTo參數:

constructor(route: ActivatedRoute, router: Router) {} 

navigate() { 
    this.router.navigate(['../'], { relativeTo: route }); 
} 

relativeTo通過創建相對於您提供的任何條目的路徑,它不一定需要成爲當前路線。

+0

this.router.navigate(['../'])不會引發錯誤,但會將我引導至我的主頁。 this.router.navigate(['../ collections'])雖然不起作用,但會引發與上述相同的錯誤。然後我嘗試了ActivatedRoute:導入它(從'@ angular/router'; import {ActivatedRoute})並將其放入構造函數中,但「relativeTo:route」引發語法錯誤:無法找到名稱「route」any。雖然它正確地寫在構造函數中:route:ActivatedRoute。你有預感,爲什麼它的行爲如此? – user3255061

+0

嘗試將'route'更改爲'this.route'。我比我想承認的更頻繁地犯這個錯誤。 – tgrass12

+0

這可能很尷尬,但我不知道我在做什麼錯誤的語法。必須是一件小事,但我沒有看到它。由於它與原始問題無關,所以我認爲最好將它發佈到pastebin上:https://pastebin.com/CY3M2Gvk。你能在那裏發現任何明顯的錯誤嗎? – user3255061