Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/406.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 角度5删除查询参数_Javascript_Angular_Typescript - Fatal编程技术网

Javascript 角度5删除查询参数

Javascript 角度5删除查询参数,javascript,angular,typescript,Javascript,Angular,Typescript,如何从URL中删除查询参数?例如,从www.expample.com/home?id=123&pos=sd&sd=iii到www.expample.com/home?id=123&sd=iii 编辑: 这是我的版本: this.activatedRoute.queryParams.subscribe(c => { const params = Object.assign({}, c); delete params.dapp; this.router.navigate([], {

如何从URL中删除查询参数?例如,从
www.expample.com/home?id=123&pos=sd&sd=iii
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下面的答案是最新的正确方法:


不幸的是,目前没有明确的方法来做到这一点:。然而,正如jasonaden对链接线程的评论一样

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

有一种方法可以做到这一点:

假设您的查询参数存储在某些属性中

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
查询参数,同时保持其他查询参数不变。

您可以通过使用
queryparammandling
merge
选项来删除查询参数,并为要删除的任何参数传入
null

// Remove query params
this.router.navigate([], {
  queryParams: {
    'yourParamName': null,
    'youCanRemoveMultiple': null,
  },
  queryParamsHandling: 'merge'
})

此选项更简单,需要更少的工作来确保不删除其他参数。当您的组件被销毁时,您也不必担心清理可观察订阅。

这是我找到的最好的解决方案,您可以更改url参数

在构造函数中使用

    private _ActivatedRoute: ActivatedRoute
然后在init或构造函数体中使用它

    var snapshot = this._ActivatedRoute.snapshot;
    const params = { ...snapshot.queryParams };
    delete params.pos
    this.router.navigate([], { queryParams: params });

您可以使用本机javascript操作从url中删除查询参数,并使用
navigateByUrl
方法导航到视图


我已经编写了一些路由器原型覆盖,使处理查询参数更容易:

其思想是在路由器上调用一个方法,以便通过参数轻松管理路由,而不是每次都必须导出功能/重新声明功能

创建包含原型覆盖定义的
index.d.ts
文件:

// Ensure this is treated as a module.
export { };

declare module '@angular/router' {
    interface Router {
        updateQueryParams(activatedRoute: ActivatedRoute, params: Params): Promise<boolean>;
        setQueryParams(activatedRoute: ActivatedRoute, params: Params): Promise<boolean>;
        removeQueryParams(activatedRoute: ActivatedRoute, ...keys: string[]): Promise<boolean>;
    }
}
原型功能实现 原型功能实现 原型功能实现
Router.prototype.removeQueryParams=函数(activatedRoute:activatedRoute,…键:字符串[]):承诺{
const context:Router=this;
const currentParams:any={};
Object.key(activatedRoute.snapshot.queryParams).forEach(key=>{
currentParams[key]=activatedRoute.snapshot.queryParams[key];
});
密钥?.forEach(密钥=>{
删除当前参数[键];
});
返回新承诺((解决)=>{
设置超时(()=>
解析(context.setQueryParams(activatedRoute,currentParams))
);
});
};
删除查询参数:

从'@angular/Router'导入{Router,ActivatedRoute,Params};
构造函数(专用路由器:路由器,专用activatedRoute:activatedRoute){
}
setQueryParams(){
常量qParams:Params={};
此.router.navigate([]{
relativeTo:this.activatedRoute,
queryParams:qParams,
查询参数:“”
});
}

谢谢,你帮我。很乐意帮忙,考虑一下点击“复选”来“接受”答案,其他人知道你的问题已经被回答了。欢迎来到SO!这泄露了一个可观察到的订阅
Router
不会自动清理对
route.url.subscribe
的订阅,并且必须在组件销毁时手动跟踪和处理。请考虑下面我的答案,它不需要任何订阅,而且更简单。感谢链接@ VcEnEny想法如何从一个数组中的查询参数中删除一个项目(例如,给出代码< >路径> p= a & p=b&p=c<代码>,如何只删除<代码> p= c<代码>代码>?当您有来自应用程序其他部分的动态查询参数,并且您只想删除非常特定的参数,而不干扰其他地方可能添加的参数时,这种方法尤其有效。这应该是正确的答案。值得注意的是,这将触发导航事件。我在清除angular guard内的参数时遇到问题-导航被取消您可以使用选项
skipLocationChange
来防止它触发导航事件。
// Ensure this is treated as a module.
export { };

declare module '@angular/router' {
    interface Router {
        updateQueryParams(activatedRoute: ActivatedRoute, params: Params): Promise<boolean>;
        setQueryParams(activatedRoute: ActivatedRoute, params: Params): Promise<boolean>;
        removeQueryParams(activatedRoute: ActivatedRoute, ...keys: string[]): Promise<boolean>;
    }
}
this.router.setQueryParams(this.activatedRoute, { param3: 'HelloWorld' });

// Will route to http://localhost:4200/#/some-route?param3=HelloWorld
Router.prototype.setQueryParams = function (activatedRoute: ActivatedRoute, params: Params): Promise<boolean> {
    const context: Router = this;

    if (isNullOrUndefined(activatedRoute)) {
        throw new Error('Cannot update the query parameters - Activated Route not provided to use relative route');
    }

    return new Promise<boolean>((resolve) => {
        setTimeout(() => {
            resolve(context.navigate([], {
                relativeTo: activatedRoute,
                queryParams: params
            }));
        });
    });
};
this.router.updateQueryParams(this.activatedRoute, { param1: 'HelloWorld' });

// Will route to http://localhost:4200/#/some-route?param1=HelloWorld&param2=test2
Router.prototype.updateQueryParams = function (activatedRoute: ActivatedRoute, params: Params): Promise<boolean> {
    const context: Router = this;

    if (isNullOrUndefined(activatedRoute)) {
        throw new Error('Cannot update the query parameters - Activated Route not provided to use relative route');
    }

    // setTimeout required because there is an unintended behaviour when rapidly firing router updates in the same repaint cycle:
    // 
    // NavigationCancel - Navigation ID 2 is not equal to the current navigation id 3
    // https://stackoverflow.com/a/42802182/1335789
    return new Promise<boolean>((resolve) => {
        setTimeout(() => {
            resolve(context.navigate([], {
                relativeTo: activatedRoute,
                queryParams: params,
                queryParamsHandling: 'merge'
            }));
        });
    });
};
this.router.removeQueryParams(this.activatedRoute, 'param1');

// Will route to http://localhost:4200/#/some-route?param2=test2&param3=test3

//Removing multiple parameters:
this.router.removeQueryParams(this.activatedRoute, 'param1', 'param3');

// Will route to http://localhost:4200/#/some-route?param2=test2
Router.prototype.removeQueryParams = function (activatedRoute: ActivatedRoute, ...keys: string[]): Promise<boolean> {
    const context: Router = this;

    const currentParams: any = {};
    Object.keys(activatedRoute.snapshot.queryParams).forEach(key => {
        currentParams[key] = activatedRoute.snapshot.queryParams[key];
    });
    keys?.forEach(key => {
        delete currentParams[key];
    });

    return new Promise<boolean>((resolve) => {
        setTimeout(() =>
            resolve(context.setQueryParams(activatedRoute, currentParams))
        );
    });
};