如何在 Angular 8 中的查询参数之前添加片段

问题描述 投票:0回答:2

我想使用片段和查询参数从组件导航到其他路径。所以这里想在查询参数之前添加片段,如下所示

http://localhost:4200/home#example?fromDate=2020-03-19&toDate=2020-03-22

我已添加查询参数,但无法在查询参数之前添加片段。我使用了 NavigationExtras 它在查询参数后添加片段。

angular angular-ui-router
2个回答
1
投票

你尝试过吗

this.router.navigate(['/home'], { fragment: 'example', queryParams: { page: 1, next: 2 } });

或者天真的方式,

this.router.navigate(['/home#example'], { queryParams: { page: 1, next: 2 } });

0
投票

组件

@Component({
  ...
  imports: [
    RouterLink
  ],
  ...
})
export class Component {
  constructor(
    private location: Location,
    private router: Router,
    private route: ActivatedRoute
  ) {}

  addFragmentToUrl(fragment: string): void {
    const currentUrlTree = this.router.createUrlTree(
      this.route.snapshot.url.map(u => u.path),
      {
        fragment,
        queryParams: this.route.snapshot.queryParams,
        queryParamsHandling: 'merge',
      }
    );

    this.location.go(currentUrlTree.toString());
  }
}

模板

<a target="_blank"
   (click)="addFragmentToUrl(data.id)"
>
  {{ data.text }}
</a>
© www.soinside.com 2019 - 2024. All rights reserved.