0

I want to pass a parameter in my URL when a search button is clicked. I wanted it to look like this. /result?search=sap

However, I am getting this error in console. Error: Cannot match any routes. URL Segment: 'result;search=sap' I can't figure out what I'm doing wrong. Here is my code.

SearchComponent.ts

search(){
    //this function is accessed when a user clicks on a search button in the HTML
    this.router.navigate(['/result', { search: this.query }]);
    //this.query = sap
}

AppModule.ts

 const routes: Routes = [
    //other routes here
  { path: 'result/:search', component: SearchComponent}
 ];

@NgModule({
  declarations: [
    //other components
    SearchComponent
  ] ,
  imports: [
    //other modules
    RouterModule.forRoot(routes, {}),

  ],
  • You are mixing required parameter syntax (with the `:search` on the route) with optional parameter syntax in the `this.router.navigate`. See this post that outlines which syntax goes with which route parameter type: https://stackoverflow.com/questions/44864303/sending-data-with-route-navigate-in-angular-2/44865817#44865817 – DeborahK Mar 07 '18 at 04:26

2 Answers2

0

If you want query parameters, your route configuration needs to look like this:

 const routes: Routes = [
    //other routes here
  { path: 'result', component: SearchComponent}
 ];

Query parameters are optional, so are not included in the route configuration.

And the syntax for query parameters in the navigate is as follows:

this.router.navigate(['/result'], 
                     {queryParams: { search: this.query }});

The resulting URL then should look something like this:

http://localhost:4200/result?search=sap

See this post for more information: Sending data with route.navigate in Angular 2

DeborahK
  • 57,520
  • 12
  • 104
  • 129
0

What you are doing is mixing 2 different url parameters technique.

1. { path: 'result/:search', component: SearchComponent} This is parameterized url technique. Itt means that this url must always have something after result part.

For ex:

result/qwe ( here qwe will get mapped to search)

result/asdasd ( here asdasd will get mapped to search )

result ( this is error since there is no part after result)

2. result?search=qwe

Here, the parameter search is optional.If you want your url to work like /result?search=qwer, then a. Keep your routes to { path: 'result', component: SearchComponent}. b. Use param of Route or ActivatedRoute. Like this.route.param.subscribe(param => console.log(param))

Shadab Faiz
  • 2,380
  • 1
  • 18
  • 28