Angular 2 Request Parameter Based Routing

Is it possible in Angular 2 to determine routing based on query parameters? I would like to have the following behavior:

If the user enters url http:<server-path>/search, I would like to go to the component StartPage.

If the user enters url http:<server-path>/search?query=sometext, I would like to go to ResultList.

I know that you can use route parameters for routing, but that’s not what I like to do. I want to use query parameters if possible. I know how to start navigation in Angular with query parameters, but I don't know how to configure routes.

+6
source share
3 answers

, path , matcher , ResultList. search, , , .

{
    component: ResultListComponent,
    matcher: (url: UrlSegment[]) => {
      console.log(url);
      return url.length === 1 && url[0].path.indexOf('search?query=') > -1 ? ({consumed: url}) : null;
    }
},
{
    path: 'search',
    component: SearchComponent,
}

+7

, .

, url:

http://localhost:4200/myUrl?QueryParamEx=2258

ROUTER

constructor(...private router: Router..){...}

URL

goMyUrl() {
  this.router.navigate(['/myUrl'], { queryParams: { QueryParamEx: '2258' } });
}
+1

- :

{ path: 'server-path/:id', component: ResultListComponent },
{ path: 'server-path', component: serverPathComponent },

ResultListComponent

queryParam: string;
    ngOnInit() {     
           this.route.params.forEach((params: Params) => {
               this.queryParam = params['id'];

           });
       }

-, , Param.

More information about query parameters can be found in the Routing and Navigation Guide.

0
source

Source: https://habr.com/ru/post/1015066/


All Articles