Angular 5删除查询参数

新手上路,请多包涵

如何从 URL 中删除查询参数?例如从 www.expample.com/home?id=123&pos=sd&sd=iiiwww.expample.com/home?id=123&sd=iii

编辑:这是我的版本:

 this.activatedRoute.queryParams.subscribe(c => {
  const params = Object.assign({}, c);
  delete params.dapp;
  this.router.navigate([], { relativeTo: this.activatedRoute, queryParams: params });
}).unsubscribe();

原文由 Nazar Kalytiuk 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 921
2 个回答

更新: @epelc 下面的答案是最新且正确的方法: https ://stackoverflow.com/a/52193044/5932590。


不幸的是,目前没有明确的方法可以做到这一点: https ://github.com/angular/angular/issues/18011。然而,正如 jasonaden 在链接线程上评论的那样,

这可以通过合并新旧查询参数来手动完成,删除您不想要的键。

这是一种方法:

假设您将 queryParams 存储在某些属性中。

 class MyComponent() {
  id: string;
  pos: string;
  sd: string;

  constructor(private route: ActivatedRoute, private router: Router) {}

  ngOnInit() {
    this.route.url.subscribe(next => {
      const paramMap = next.queryParamMap;
      this.id = paramMap.get('id');
      this.pos = paramMap.get('pos');
      this.sd = paramMap.get('sd');
    });
  }
}

清除 pos 参数的方法如下所示:

 clearPosParam() {
  this.router.navigate(
    ['.'],
    { relativeTo: this.route, queryParams: { id: this.id, sd: this.sd } }
  );
}

这将有效地导航到当前路由并清除您的 pos 查询参数,保持其他查询参数相同。

原文由 vince 发布,翻译遵循 CC BY-SA 4.0 许可协议

我正在寻找这样做,但不使用路由器。这是我想出的:

 import { Location } from '@angular/common';
import { HttpParams } from '@angular/common/http';

declare location: Location; // get this from dependency injection

const [path, query] = location.path().split('?');
const params = new HttpParams({ fromString: query });
const theValueIWant = params.get('theParamIWant');
location.replaceState(path, params.delete('theParamIWant').toString());

原文由 Eric Simonton 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题