Angular 5 删除查询参数 [英] Angular 5 remove query param

查看:25
本文介绍了Angular 5 删除查询参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How would I remove a query parameter from the URL? For example from www.expample.com/home?id=123&pos=sd&sd=iii to www.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();

推荐答案

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

UPDATE: @epelc's answer below is the up-to-date and correct way to do this: https://stackoverflow.com/a/52193044/5932590.

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

Unfortunately, there is no clear-cut way to do this currently: https://github.com/angular/angular/issues/18011. However, as jasonaden commented on the linked thread,

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

This could be done manually by merging the old and new query params, removing the key you don't want.

这是一种方法:

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

Let's say you have your queryParams stored in some properties.

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 参数的方法如下所示:

A method to clear the pos parameter would look like this:

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

这将有效地导航到当前路线并清除您的 pos 查询参数,使您的其他查询参数保持不变.

This will effectively navigate to the current route and clear your pos query parameter, keeping your other query parameters the same.

这篇关于Angular 5 删除查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆