Optional Parameters While Routing angular2 [duplicate]

馋奶兔 提交于 2020-01-16 00:44:42

问题


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



来源:https://stackoverflow.com/questions/36098680/optional-parameters-while-routing-angular2

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