当我想在我的 URL 中传递参数时,读取了错误的 URL
Wrong URL is read when I want to pass a parameter in my URL
我想在单击搜索按钮时在 URL 中传递一个参数。
我希望它看起来像这样。
/result?search=sap
但是,我在控制台中收到此错误。
错误:无法匹配任何路由。 URL 细分:'result;search=sap'
我不知道我做错了什么。这是我的代码。
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, {}),
],
如果你想要查询参数,你的路由配置需要如下所示:
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
有关详细信息,请参阅此 post:
您正在做的是混合 2 种不同的 url 参数技术。
1. { 路径:'result/:search',组件:SearchComponent}
这是参数化 url 技术。 Itt 意味着这个 url 必须总是在结果部分之后有一些东西。
例如:
result/qwe(这里 qwe 将映射到搜索)
result/asdasd(此处 asdasd 将映射到搜索)
结果(这是错误,因为结果后面没有部分)
2。结果?搜索=qwe
在这里,参数 search 是 optional.If 您希望 url 像 /result?search=qwer, 那么
一种。保持你的路由到 { path: 'result', component: SearchComponent}。
b.使用 Route 或 ActivatedRoute 的参数。比如 this.route.param.subscribe(param => console.log(param))
我想在单击搜索按钮时在 URL 中传递一个参数。 我希望它看起来像这样。 /result?search=sap
但是,我在控制台中收到此错误。 错误:无法匹配任何路由。 URL 细分:'result;search=sap' 我不知道我做错了什么。这是我的代码。
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, {}),
],
如果你想要查询参数,你的路由配置需要如下所示:
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
有关详细信息,请参阅此 post:
您正在做的是混合 2 种不同的 url 参数技术。
1. { 路径:'result/:search',组件:SearchComponent} 这是参数化 url 技术。 Itt 意味着这个 url 必须总是在结果部分之后有一些东西。
例如:
result/qwe(这里 qwe 将映射到搜索)
result/asdasd(此处 asdasd 将映射到搜索)
结果(这是错误,因为结果后面没有部分)
2。结果?搜索=qwe
在这里,参数 search 是 optional.If 您希望 url 像 /result?search=qwer, 那么 一种。保持你的路由到 { path: 'result', component: SearchComponent}。 b.使用 Route 或 ActivatedRoute 的参数。比如 this.route.param.subscribe(param => console.log(param))