简体   繁体   中英

Angular “Error: Cannot match any routes. URL Segment” when using [routerLink], but it works with this.router.navigate

I have a primary and a named outlet in my application defined as follows:

<router-outlet></router-outlet>
<router-outlet name="center"></router-outlet>

I have defined a route to be used with this center component in my app-routing:

const routes: Routes = [
{ path: 'login', component: LoginComponent, outlet: 'center' },   
{ path: 'home',  component: HomeComponent },
{ path: 'car',       component: BaseComponent },
{ path: 'car/:id',   component: CarComponent },
{ path: 'gi/:otherId',component:GIComponent, outlet: 'center' },
{ path: '', pathMatch: 'full', redirectTo: 'home' }];

I am defining a link in Car.component.html to route a GI component to the named outlet. But this link gives me an error:

<a [routerLink]="[{ outlets: { center: ['gi', myObject.id] } }]" > GI Link </a>

However, I am able to create a function to perform this navigation using router.navigate():

<a [routerLink]="" (click)="routeGI()" > Gi Link  </a>

...and the associated function in my Car.Component.ts file:

routeGI() { this.router.navigate([{ outlets: {center: ['gi', this.myObject.id]  }}]);

So the function routeGI() works like a charm, but the navigation from html using [routerLink] gives me the following exception:

ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 
'car/2112'
Error: Cannot match any routes. URL Segment: 'car/2112'
at ApplyRedirects.push../node_modules/@angular/router/fesm5/router.js.ApplyRedirects.noMatchError 
(router.js:2464)
at CatchSubscriber.selector (router.js:2445)
at CatchSubscriber.push../node_modules/rxjs/_esm5/internal/operators/catchError.js.CatchSubscriber.error (catchError.js:34)
at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._error (Subscriber.js:79)

Shouldn't these links to my named outlet both work?

Answered by this more specific question with a StackBlitz example showing the problem: Routing to a named outlet from links in a navigation component fails only when using [routerLink]

add empty string before the outlet like bellow

[routerLink]="['', { outlets: { center: ['gi', '10'] } }]"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM