Angular2 RouterLink breaks routes by replacing slash with %2F

杀马特。学长 韩版系。学妹 提交于 2019-12-17 20:50:05

问题


Since the latest Angular2 version (2.0.0-beta.14) it is possible to have query parameters that contain multiple slashes, like /foo/bar.

This works great, however whenever I use a parameter with multiple slashes within a RouterLink link, it escapes the / with %2F causing the routes to not work anymore on reload.

My link looks like this: <a [routerLink]="['/Page', {page: page.url | slug}]" class="list-group-item">{{ page.title }}</a>

Inside of the 'slug' pipe I even URIDecode the string, and when I log it it is correct. It would log something like /pages/level-1/, but when I inspect the actual a tag on the page it says href="/pages%2Flevel-1".

I'm pretty clueless, because even when I print the value of {{ page.url | slug }} within my HTML template, it returns the url with slashes.


回答1:


So I found the solution thanks to the Angular2 Issues page on Github (thanks Günter!).

My route was configured like this:

({ 
    path: "/:page",
    component: Page,
    name: "Page"
}),

but instead should have been

({
    path: "/*page",
    component: Page,
    name: "Page"
}),

Difference is the * wildcard in front of page.

I created this issue




回答2:


If the path was something like

pathServedByTheController = 'foo/bar'

then in the view I can do something like

<my-button (click)="onEmitCta()" [routerLink]="['/'].concat(pathServedByTheController.split('/')).concat('')" class="banner-cta inverse shadow">NAVIGATE</my-button>

This works nicely to me!




回答3:


Instead of trying to use strings with slashes in routerLink, we simply let the router handle it in the component.

<a (click)="goToPage(url)">Link</a>
url = 'group/8';

goToPage(url) {
    this.router.navigateByUrl(url);
}


来源:https://stackoverflow.com/questions/36597832/angular2-routerlink-breaks-routes-by-replacing-slash-with-2f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!