Nice programing

Angular : 경로를 변경하지 않고 queryParams를 업데이트하는 방법

nicepro 2020. 10. 15. 21:39
반응형

Angular : 경로를 변경하지 않고 queryParams를 업데이트하는 방법


구성 요소에서 queryParams를 업데이트 (추가, 제거)하려고합니다. angularJS에서는 다음 덕분에 가능했습니다.

$location.search('f', 'filters[]'); // setter
$location.search()['filters[]'];    // getter

사용자가 필터링, 주문 등을 할 수있는 목록이있는 앱이 있으며 URL의 queryParams에 활성화 된 모든 필터를 설정하여 URL을 복사 / 붙여 넣기하거나 다른 사람과 공유 할 수 있습니다.

그러나 필터를 선택할 때마다 내 페이지가 다시로드되는 것을 원하지 않습니다 .

새로운 라우터로 가능합니까?


페이지를 다시로드하지 않지만 쿼리 매개 변수를 업데이트하는 새 쿼리 매개 변수를 사용하여 현재 경로로 이동할 수 있습니다.

다음과 같은 것 (구성 요소에서) :

constructor(private router: Router) { }

public myMethodChangingQueryParams() {
  const queryParams: Params = { myParam: 'myNewValue' };

  this.router.navigate(
    [], 
    {
      relativeTo: activatedRoute,
      queryParams: queryParams, 
      queryParamsHandling: 'merge', // remove to replace all query params by provided
    });
}

페이지를 다시로드하지는 않지만 브라우저 기록에 새 항목을 푸시합니다. 새 값을 추가하는 대신 기록에서 대체하려면 { queryParams: queryParams, replaceUrl: true }.

편집 :로 이미 의견에서 지적 []하고 relativeTo그것뿐만 아니라 쿼리 PARAMS을 경로를 변경 수 있도록 속성이, 내 원래의 예에서 누락되었습니다. this.router.navigate이 경우 적절한 사용법은 다음과 같습니다.

this.router.navigate(
  [], 
  {
    relativeTo: this.activatedRoute,
    queryParams: { myParam: 'myNewValue' },
    queryParamsHandling: 'merge'
  });

새 매개 변수 값을로 설정하면 nullURL에서 매개 변수 가 제거됩니다.


@ Radosław Roszkowiak의 대답은 relativeTo: this.route아래와 같이 필요한 것을 제외하고 거의 옳습니다 .

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

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

Angular 5에서는 현재 URL을 구문 분석하여 urlTree 의 복사본을 쉽게 얻고 수정할 수 있습니다 . 여기에는 쿼리 매개 변수와 조각이 포함됩니다.

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

  this.router.navigateByUrl(urlTree); 

쿼리 매개 변수를 수정하는 "올바른 방법"은과 아마 createUrlTree 우리가 사용하여 수정시키는 동안 현재에서 새 UrlTree을 만들어 같은 그 이하 NavigationExtras을 .

import { Router } from '@angular/router';

constructor(private router: Router) { }

appendAQueryParam() {

  const urlTree = this.router.createUrlTree([], {
    queryParams: { newParamKey: 'newValue' },
    queryParamsHandling: "merge",
    preserveFragment: true });

  this.router.navigateByUrl(urlTree); 
}

이 방법으로 쿼리 매개 변수를 제거하려면 undefined또는로 설정할 수 있습니다 null.


경로를 변경하지 않고 쿼리 매개 변수를 변경하려는 경우. 아래 예제를 참조하면 도움이 될 수 있습니다. 현재 경로는 : / search & 대상 경로는 (페이지를 다시로드하지 않음) : / search? query = love

submit(value: string) {
{ this.router.navigate( ['.'],  { queryParams: { query: value } })
    .then(_ => this.search(q));
}
search(keyword:any) { 
//do some activity using }

참고 : this.router.navigate ([ '.'] 대신 this.router.navigate ([ 'search'])사용할 수 있습니다 .


The answer with most vote partially worked for me. The browser url stayed the same but my routerLinkActive was not longer working after navigation.

My solution was to use 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());
  }
}

I used HttpParams to build the query string since I was already using it to send information with httpClient. but you can just build it yourself.

and the this._router.url.split("?")[0], is to remove all previous query string from current url.


Try

this.router.navigate([], { 
  queryParams: {
    query: value
  }
});

will work for same route navigation other than single quotes.


First, we need to import the router module from angular router and declare its alias name

import { Router } from '@angular/router'; ---> import
class AbcComponent implements OnInit(){
constructor(
    private router: Router ---> decalre alias name
  ) { }
}

1. You can change query params by using "router.navigate" function and pass the query parameters

this.router.navigate([], { queryParams: {_id: "abc", day: "1", name: "dfd"} 
});

It will update query params in the current i.e activated route

  1. The below will redirect to abc page with _id, day and name as query params

    this.router.navigate(['/abc'], { queryParams: {_id: "abc", day: "1", name: "dfd"} });

    It will update query params in the "abc" route along with three query paramters

For fetching query params:-

    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 : https://stackoverflow.com/questions/43698032/angular-how-to-update-queryparams-without-changing-route

반응형