我想在单击搜索按钮时在我的 URL 中传递一个参数。我希望它看起来像这样。/result?search=sap
但是,我在控制台中收到此错误。错误:无法匹配任何路由。URL Segment: 'result;search=sap' 我不知道我做错了什么。这是我的代码。
搜索组件.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, {}),
],
如果您需要查询参数,您的路由配置需要如下所示:
const routes: Routes = [
//other routes here
{ path: 'result', component: SearchComponent}
];
查询参数是可选的,因此不包含在路由配置中。
中查询参数的语法navigate
如下:
this.router.navigate(['/result'],
{queryParams: { search: this.query }});
生成的 URL 应如下所示:
http://localhost:4200/result?search=sap
有关更多信息,请参阅此帖子:在 Angular 2 中使用 route.navigate 发送数据
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句