Angular 角度:如何在不更改路由的情况下更新queryParams

Angular 角度:如何在不更改路由的情况下更新queryParams,angular,query-parameters,angular-router,Angular,Query Parameters,Angular Router,我正在尝试从组件中更新(添加、删除)queryParams。在angularJS中,由于以下原因,它过去是可能的: $location.search('f', 'filters[]'); // setter $location.search()['filters[]']; // getter 我有一个带有列表的应用程序,用户可以过滤、排序等,我想在url的查询参数中设置所有激活的过滤器,以便他可以复制/粘贴url或与其他人共享 但是,我不希望每次选择过滤器时都重新加载我的页面 这在新路由

我正在尝试从组件中更新(添加、删除)queryParams。在angularJS中,由于以下原因,它过去是可能的:

$location.search('f', 'filters[]'); // setter
$location.search()['filters[]'];    // getter
我有一个带有列表的应用程序,用户可以过滤、排序等,我想在url的查询参数中设置所有激活的过滤器,以便他可以复制/粘贴url或与其他人共享

但是,我不希望每次选择过滤器时都重新加载我的页面


这在新路由器上可行吗?

您可以使用新的查询参数导航到当前路由,它不会重新加载页面,但会更新查询参数

类似于(在组件中):

构造函数(专用路由器:路由器){}
公共myMethodChangingQueryParams(){
常量queryParams:Params={myParam:'myNewValue'};
这是路由器(
[], 
{
relativeTo:activatedRoute,
queryParams:queryParams,
queryParamsHandling:'merge',//删除以替换提供的所有查询参数
});
}
请注意,虽然它不会重新加载页面,但会将新条目推送到浏览器的历史记录中。如果要在历史记录中替换它而不是在历史记录中添加新值,可以使用
{queryParams:queryParams,replaceUrl:true}

编辑: 正如注释中已经指出的那样,
[]
relativeTo
属性在我的原始示例中丢失,因此它也可以更改路由,而不仅仅是查询参数。在这种情况下,
this.router.navigate
的正确用法是:

this.router.navigate(
[], 
{
relativeTo:this.activatedRoute,
queryParams:{myParam:'myNewValue'},
查询参数:“合并”
});

将新参数值设置为
null
将从URL中删除参数。

在Angular 5中,您可以通过解析当前URL轻松获取和修改的副本。这将包括查询参数和片段

  let urlTree = this.router.parseUrl(this.router.url);
  urlTree.queryParams['newParamKey'] = 'newValue';

  this.router.navigateByUrl(urlTree); 
修改查询参数的“正确方法”可能是使用 如下所示,它从当前URL创建了一个新的UrlTree,同时允许我们使用


为了以这种方式删除查询参数,如果要在不更改路由的情况下更改查询参数,可以将其设置为
undefined
null

。见下文 示例可能会帮助您: 当前路线为:
/search
&目标路线是(无重新加载页面):
/search?query=love

submit(值:字符串){
this.router.navigate(['.],{queryParams:{query:value})
.然后(=>this.search(q));
}
搜索(关键字:any){
//使用}执行一些活动

请注意:您可以使用
this.router.navigate(['search']
而不是
this.router.navigate(['.]
@Radosław Roszkowiak的答案几乎是正确的,除了以下所需的
相对:this.route

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

changeQuery() {
  this.router.navigate(['.'], { relativeTo: this.route, queryParams: { ... }});
}
试一试


将用于除单引号以外的同一路线导航。

首先,我们需要从angular router导入路由器模块并声明其别名

import { Router } from '@angular/router'; ---> import
class AbcComponent implements OnInit(){
constructor(
    private router: Router ---> decalre alias name
  ) { }
}
1.您可以使用“router.navigate”功能更改查询参数并传递查询参数

this.router.navigate([], { queryParams: {_id: "abc", day: "1", name: "dfd"} 
});
它将更新当前即激活路由中的查询参数

  • 以下内容将重定向到带有_id,day的abc页面 和名称作为查询参数

    this.router.navigate(['/abc'],{queryParams:{u id:“abc”,day:“1”,name: “dfd”} }))

    它将更新“abc”路由中的查询参数以及三个查询参数

  • 用于获取查询参数:-

        import { ActivatedRoute } from '@angular/router'; //import activated routed
    
        export class ABC implements OnInit {
    
        constructor(
            private route: ActivatedRoute //declare its alias name
          ) {}
    
        ngOnInit(){
           console.log(this.route.snapshot.queryParamMap.get('_id')); //this will fetch the query params
        }
    

    大多数人投票的答案对我部分有效。浏览器url保持不变,但我的
    routerLinkActive
    在导航后不再有效

    我的解决方案是使用lotation.go:

    import { Component } from "@angular/core";
    import { Location } from "@angular/common";
    import { HttpParams } from "@angular/common/http";
    
    export class whateverComponent {
      constructor(private readonly location: Location, private readonly router: Router) {}
    
      addQueryString() {
        const params = new HttpParams();
        params.append("param1", "value1");
        params.append("param2", "value2");
        this.location.go(this.router.url.split("?")[0], params.toString());
      }
    }
    
    我使用HttpParams来构建查询字符串,因为我已经在使用它与httpClient发送信息。但是您可以自己构建它


    this.\u router.url.split(“?”[0]
    ,是从当前url中删除所有以前的查询字符串。

    我最终将
    urlTree
    location.go

    const urlTree = this.router.createUrlTree([], {
           relativeTo: this.route,
           queryParams: {
               newParam: myNewParam,
           },
           queryParamsHandling: 'merge',
        });
    
        this.location.go(urlTree.toString());
    

    不确定
    toString
    是否会导致问题,但不幸的是
    location.go
    ,似乎是基于字符串的。

    更好-只是HTML:

    您的查询参数链接


    请注意空数组,而不是只执行
    routerLink=“”
    [routerLink]=“''''

    我必须使用
    []
    而不是
    ['.]
    来使其工作需要使用queryParams['relativeTo']=this.activatedRoute;使相对于当前页面的导航成为解决OP问题的最佳解决方案。除非我遗漏了什么,否则它无法让您在当前页面的历史记录中前后移动(例如,更改了5次筛选器或订单,每个都有自己的URL,但有相同的组件)我想你可以通过
    this.activatedRoute.queryParams.subscribe
    手动完成这项工作,并在你的组件中进行各种更新,但是有没有一种简单的角度方法来加载路由,以便来回自动工作每次更改url参数时,都会破坏组件并调用ngOnit()。有没有办法避免调用ngOnit()?当使用router.navigate时,它会滚动到窗口顶部,有没有办法禁用此功能?
    navigateByUrl
    navigate
    -不仅仅是UrlTree参数。请参阅我不确定[。]是一种比
    relativeTo:
    更好的方法,但是
    .then()
    很有帮助-不知道navigate()返回了一个承诺,很高兴您发布了!我们可以使用['.]或['search'],而不是使用['.]或['search']这应该是可接受的答案,router.navigates也会刷新ngOnit,location.go不会这样做!这真是我的错
    import { Component } from "@angular/core";
    import { Location } from "@angular/common";
    import { HttpParams } from "@angular/common/http";
    
    export class whateverComponent {
      constructor(private readonly location: Location, private readonly router: Router) {}
    
      addQueryString() {
        const params = new HttpParams();
        params.append("param1", "value1");
        params.append("param2", "value2");
        this.location.go(this.router.url.split("?")[0], params.toString());
      }
    }
    
    const urlTree = this.router.createUrlTree([], {
           relativeTo: this.route,
           queryParams: {
               newParam: myNewParam,
           },
           queryParamsHandling: 'merge',
        });
    
        this.location.go(urlTree.toString());