代码之家  ›  专栏  ›  技术社区  ›  OrdinaryProgrammer

当我要在URL中传递参数时,读取了错误的URL

  •  0
  • OrdinaryProgrammer  · 技术社区  · 7 年前

    单击搜索按钮时,我想在URL中传递一个参数。 我想让它看起来像这样。 /结果如何?搜索=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, {}),
    
      ],
    
    2 回复  |  直到 7 年前
        1
  •  0
  •   DeborahK    7 年前

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

     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
  •  0
  •   Shadab Faiz    7 年前

    您所做的是混合使用两种不同的url参数技术。

    1.{路径:'结果/:搜索',组件:搜索组件} 这是参数化url技术。Itt意味着此url必须始终在结果部分之后包含某些内容。

    对于ex:

    结果/qwe(这里qwe将映射到搜索)

    结果/asdasd(此处asdasd将映射到搜索)

    结果(这是错误,因为结果后没有零件)

    2、结果?搜索=qwe

    这里,参数 搜索 是可选的。如果你想让你的url像 /结果如何?搜索=qwer 然后 a、 保持您的路线 {路径:“结果”,组件:SearchComponent} 。 b、 使用Route或ActivatedRoute的参数。喜欢 这路线参数。订阅(参数=>控制台日志(参数))