2017-09-13 169 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