Angular 2 Adds Trailing Slash To URL With Multiple

2019-05-04 18:43发布

问题:

I have an app component that has two outlets:

template: '<router-outlet></router-outlet><router-outlet name="popup"></router-outlet>'

I followed the example in this link to create the routing and the routerLinks and everything works fine as long as the routerLinks are inside the app component. However, I have created a main layout component with a menu inside so that I can reuse it on all the pages and use loadChildren to load the corresponding modules and components inside.

<app-main-menu></app-main-menu>
<h1>
  {{title}}
</h1>
<div class="container">
  <router-outlet></router-outlet>
</div>

The problem is that when I move the routerLinks for the popup outlet into the menu, it contains a trailing slash for the main route and the resulting url does not work. So for example this routerLink:

<a [routerLink]="[{ outlets: { popup : ['login'] } }]">Login</a>

creates the url 'localhost/mainroute(popup:login)' if it is placed in the app component and 'localhost/mainroute/(popup:login)' if it is placed in the menu component.

While the first url works, the second url produces an error: Error: Cannot match any routes: 'mainroute'

I don't understand why it treats the two cases differently. I also do not understand, that even if the url 'localhost/mainroute/' works, the second generated url does not because of the the trailing slash.

Can someone help me?

回答1:

I have found this issue, which describes the exact same behavior. Apparently it has been brought to the developers attention and they consider it the right behavior. The same router link expression can produce different results depending on where it's used.

The proposed solution is to use a relative link like this:

<a [routerLink]="['../', { outlets: { popup: 'login' } }]">

or to use an absolute link like this:

<a [routerLink]="['/', { outlets: { popup: 'login' } }]">

In the case described in here the absolute link worked and gave the right link.

I still do not understand the behavior. So if anyone has a good explanation for it please elaborate.