How to pass optional Router Parameter with preserved URL in Angular5

Aja*_*nga 6 angular-routing angular angular-router angular5

I have some specific requirement in that have to work with Existing URL. Existing URL's are already well indexed and used for promotions and many campaigns so no chance to modify it.

Existing URLs is like - www.xyz.com/search//65.5445/-122.56454/Listing-name/All

While In Angular defining URL like

const routes: Routes = [
  { path: '', component: SearchpagesComponent ,
    children: [
      {
        path: 'search/:schkey/:lat/:lng/:name/:filter', loadChildren: './search/search.module#SearchModule',
        // here schkey is optinal just required blank slashes 
      }
    ]
  }
];
Run Code Online (Sandbox Code Playgroud)

and in Router link

<a [routerLink]="['/search/','','37.7749295','-122.41941550000001','San-Francisco','All']" > Goto Search Page </a>
Run Code Online (Sandbox Code Playgroud)

Current : Above code is working, If I click on Routerlink defined anchor. its redirecting and component being loaded, but on refreshing the page component is not loading and redirecting to root URL.

Expected:www.xyz.com/search//37.7749295/-122.41941550000001/San-Francisco/ on direct link or refreshing page component should be loaded. And double slashes search// should be preserved.

For Reproducing - https://stackblitz.com/edit/angular-routing-child-routes-6ydor6

Github Issue - https://github.com/angular/angular/issues/32853

Ele*_*ron 5

原因是因为:schkey留空了。

您可以定义带有或不带有某些参数的多个路由。

{
    path: 'search/:schkey/:lat/:lng/:name/:filter',
    component: SearchpageComponent
},
{
    path: 'search/:lat/:lng/:name/:filter',
    component: SearchpageComponent
}
Run Code Online (Sandbox Code Playgroud)

基本上,而不是:

http://.../search//37.7749295/-122.41941550000001/San-Francisco/All
Run Code Online (Sandbox Code Playgroud)

您的网址是:

http://.../search/37.7749295/-122.41941550000001/San-Francisco/All
Run Code Online (Sandbox Code Playgroud)


小智 0

您可以为一个组件/模块指定多个路由。一条路线将带有此参数,而第二条路线则不带有此参数。

const routes: Routes = [
  { path: '', component: SearchpagesComponent ,
    children: [
      {
        path: 'search/:schkey/:lat/:lng/:name/:filter', loadChildren: './search/search.module#SearchModule',
        path: 'search//:schkey/:lat/:lng/:name/:filter', loadChildren: './search/search.module#SearchModule',
      }
    ]
  }
];
Run Code Online (Sandbox Code Playgroud)

或者你可以通过查询字符串传递它们,就像这里How to get query params from url in Angular 2? 在这种情况下,您不需要在路由配置中指定它们