【问题标题】:Wrong URL is read when I want to pass a parameter in my URL当我想在我的 URL 中传递一个参数时,读取了错误的 URL
【发布时间】:2018-03-07 04:23:23
【问题描述】:

我想在单击搜索按钮时在我的 URL 中传递一个参数。 我希望它看起来像这样。 /result?search=sap

但是,我在控制台中收到此错误。 错误:无法匹配任何路由。 URL 段:'结果;搜索 = 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, {}),

  ],

【问题讨论】:

  • 您在this.router.navigate 中混合了必需的参数语法(与路由上的:search)和可选参数语法。请参阅这篇文章,其中概述了哪种语法与哪种路由参数类型:stackoverflow.com/questions/44864303/…

标签: angular angular5 angular-router


【解决方案1】:

如果您需要查询参数,您的路由配置需要如下所示:

 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

更多信息请看这篇文章:Sending data with route.navigate in Angular 2

【讨论】:

  • 这个解决方案效果很好。非常感谢。我想我遵循了错误的参考资料。
【解决方案2】:

您正在做的是混合 2 种不同的 url 参数技术。

1. { 路径:'result/:search',组件:SearchComponent} 这是参数化的 url 技术。这意味着这个url必须总是在结果部分之后有一些东西。

例如:

result/qwe(这里 qwe 将被映射到搜索)

result/asdasd(这里 asdasd 将被映射到搜索)

结果(这是错误,因为结果后面没有部分)

2。结果?搜索=qwe

这里,参数 search 是可选的。如果您希望您的 url 像 /result?search=qwer 一样工作,那么 一种。将您的路线保留到 { path: 'result', component: SearchComponent}。 湾。使用 Route 或 ActivatedRoute 的参数。像 this.route.param.subscribe(param => console.log(param))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-23
    • 2015-10-10
    相关资源
    最近更新 更多