Angular 2 Routing based on query params

耗尽温柔 提交于 2019-11-30 19:41:45

So you can't define a path with the query string in it but you can use a route matcher instead and determine when to route to the ResultList component. You define this above the default route definition for search so that if the match fails it will default to the search route with no query string.

{
    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,
}

Demo

BERGUIGA Mohamed Amine

In the below code I'll show how to pass query string parameters across any route.

suppose we want to have the below url:

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

In your constructor inject the ROUTER dependency

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

The navigate function will allow us to navigate to the preceding url

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

You can also setup something like this:

Routes:

{ 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'];

           });
       }

You can call whatever function or anything that you need to do using that queryParam.

More on query params can be found at the Routing & Navigation guide

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