【问题标题】:Angular 6 Routing - Query Parameters inside named secondary router outletAngular 6 Routing - 在命名的辅助路由器出口内查询参数
【发布时间】:2019-06-04 05:32:42
【问题描述】:

在 Angular 6 中,是否可以在辅助命名路由器出口中使用查询参数。我正在寻找的类型的示例 URL 是

localhost:4200/home(sidebar:chat?animal=dog)

我希望能够设置查询参数:a​​nimal,并且还能够在组件中访问其值。

到目前为止我已经在模板中尝试过

[routerLink]="gridRouterLink" [queryParams]="queryParams" 

在哪里gridRouterLink = ["", {outlets: {sidebar: "chat"}}]

queryParams = { animal: "dog"}

但我得到类似 localhost:4200/home(sidebar:chat)?animal=dog 的东西

【问题讨论】:

  • 编辑您的问题以包含您迄今为止尝试过的内容。

标签: angular


【解决方案1】:

目前使用 Angular 8,我只能使用控制器中的路由器来实现这一点。

模板:

<button (click)="testOutletModal($event)">Test</button> 

控制器:

testOutletModal($event: MouseEvent) {
  $event.preventDefault();

  const navigationExtras = { queryParams: { test: 1, project: 1 } };
  const commands = [
    {
      outlets: {
        modal: ['one', 'two', 3],
      },
    },
  ];
  this.router.navigate(commands, navigationExtras);
}

然后我的网址看起来像http://localhost:4200/(modal:one/two/3)?test=1&amp;project=1。乍一看,查询参数在出口路由信息所在的() 之外是错误的。但是,URL 只能有一个?,因此只有一个参数“数组”。

我尝试从为路由“modal:one/two/3”配置的控制器访问queryParams,它可以工作。

this.route.queryParams.subscribe(qp => {
  console.log('Query Params', qp);
})
// Query Params {test: "1", project: "1"}

看来这是实现这一目标的正确方法。

【讨论】:

    【解决方案2】:

    你可以在路由中使用参数如下:

    const routes:Routes = [
     { path: '/:id', component: ProfileComponent, name: 'Details'}
    ]
    

    在组件中获取参数

    class ProfileComponent{
    token: string;
    constructor(params: RouteParams) {
      this.token = params.get('id');
    }
    }
    

    希望这会对你有所帮助。

    【讨论】:

      猜你喜欢
      • 2019-02-19
      • 1970-01-01
      • 1970-01-01
      • 2018-07-19
      • 1970-01-01
      • 2019-05-17
      • 2018-01-23
      • 2019-09-29
      • 1970-01-01
      相关资源
      最近更新 更多