Optional Parameters While Routing angular2 [duplic

2019-08-15 18:02发布

问题:

This question already has an answer here:

  • Angular 2 optional route parameter 10 answers

How to define optional parameters in routing of angular2.my routing configuration like this:

<a [routerLink]="['../abc',{xyz: blabla}]">
     and 
<a [routerLink]="['../abc']">

{ path: '/abc/:xyz', component: abc, name: 'abc' },  // Here i want xyz as optional perameter

so the problem is whenever i am using first method with parameter blabla it works fine because at the time of routing i have defined parameter xyz but in case of second method i dont want to send parameter so the URL becomes

http://localhost:8080/#/sideNav/abc/

which is laoding first time fine but after refresh page nothing shows whole window is getting blank with no contents. so is there any method to provide optional parameters while routing in angular2.

i have also tried without defining parameters like this

{ path: '/abc', component: abc, name: 'abc' }

but this will throw error in case of value of xyz is 1 it converts 1 into true

回答1:

You can define multiple routes with and without parameter having the same component:

@RouteConfig([{
  path: '/abc',
  component: Abc,
  name: 'abc'},
{
  path: '/abc/:xyz',
  component: Abc,
  name: 'abcXyz'
}])

and then use the one that you need

<a [routerLink]="['/abcXyz',{xyz: blabla}]">
     and 
<a [routerLink]="['/abc']">

If routeCongig is located in your root file, use / before root's name and if it's on the second level or something, use

<a [routerLink]="['/parentRoot', {parentParams:value}, '/abc']">


回答2:

You can put both together,

@RouteConfig([
    { path: '/abc/:xyz', component: Abc,  name: 'abc' }
    { path: '/abc', component: Abc, name: 'abc' },
])

if this doesn't work as expected, you should see below,

Optional routeparams #3525
https://github.com/angular/angular/issues/3525