IT

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

itgroup 2023. 4. 28. 20:29
반응형

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

구성 요소에서 queryParams를 업데이트(추가, 제거)하려고 합니다.AngularJS에서는 다음과 같은 기능을 통해 가능했습니다.

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

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

그러나 필터를 선택할 때마다 페이지를 다시 로드하지 않습니다.

이것이 새 라우터로 가능합니까?

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

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

import {ActivatedRoute, Router} from '@angular/router';
constructor(
    private router: Router,
    private activatedRoute: ActivatedRoute,
) { }

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

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

페이지를 다시 로드하지는 않지만 브라우저 기록에 새 항목을 밀어넣습니다.새 값을 추가하는 대신 기록에서 바꾸려면 다음을 사용할 수 있습니다.{ queryParams: queryParams, replaceUrl: true }.

편집: 이미 댓글에서 지적했듯이,[]그리고relativeTo원래 예제에서 속성이 누락되었기 때문에 쿼리 매개 변수뿐만 아니라 경로도 변경할 수 있습니다.고유의this.router.navigate이 경우에는 다음과(와)

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

새 매개 변수 값 설정nullURL에서 매개 변수를 제거합니다.

@라도스와프 로즈코비악의 대답은 다음을 제외하고는 거의 맞습니다.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); 

쿼리 매개 변수를 수정하는 "올바른 방법"은 탐색을 사용하여 수정하는 동안 현재로부터 새 UrlTree를 만드는 아래와 같은 createUrlTree를 사용하는 것입니다.엑스트라.

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.

가장 많은 표를 얻은 답변은 부분적으로 저에게 효과가 있었습니다.브라우저 url은 동일하게 유지되었지만 나의routerLinkActive탐색 후 더 이상 작동하지 않았습니다.

제 해결책은 로테이션을 사용하는 것이었습니다.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());
  }
}

이미 httpClient로 정보를 보낼 때 사용했기 때문에 HttpParams를 사용하여 쿼리 문자열을 작성했지만, 사용자가 직접 작성할 수 있습니다.

그리고this._router.url.split("?")[0]현재 URL에서 이전 쿼리 문자열을 모두 제거합니다.

해라

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

단일 따옴표를 제외한 동일한 경로 탐색에 사용할 수 있습니다.

경로를 변경하지 않고 쿼리 매개 변수를 변경하려는 경우.아래의 예를 참조하십시오. 현재 경로는:/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( ['search']this.router.navigate( ['.']

저는 결국 결합했습니다.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:

<a [routerLink]="[]" [queryParams]="{key: 'value'}">Your Query Params Link</a>

수행하는 대신 빈 배열을 기록합니다.routerLink=""또는[routerLink]="''"

먼저 각 라우터에서 라우터 모듈을 가져와 별칭 이름을 선언해야 합니다.

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

"router.navigate" 함수를 사용하여 쿼리 매개 변수를 변경하고 쿼리 매개 변수를 전달할 수 있습니다.

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

현재 활성화된 경로에서 쿼리 매개 변수를 업데이트합니다.

  1. 아래는 _id, day 및 name을 쿼리 매개 변수로 사용하는 abc 페이지로 리디렉션됩니다.

    this.router.navigate(['/abc'), {queryParams: {_id: "abc", 일: "1", 이름: "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
    }

Angular's Location 서비스는 라우팅이 아닌 브라우저의 URL과 상호 작용할 때 사용해야 합니다.그것이 우리가 위치 서비스를 사용하려는 이유입니다.

Angulars HttpParams는 쿼리 매개 변수를 만드는 데 사용됩니다.HttpParams는 불변이므로 값을 만들 때 체인으로 연결되어야 합니다.

막으로사를 사용하여, 용지.this._location.replaceState및 js를 다시 로드하지 하려면 / native js를 js로 변경합니다.location.path매번 매개 변수를 재설정하기 위해 매개 변수가 없는 URL을 가져옵니다.

constructor(
    private _location: Location,
) {}

...

updateURLWithNewParamsWithoutReloading() {
    const params = new HttpParams().appendAll({
        price: 100,
        product: 'bag'
    });

    this._location.replaceState(
        location.pathname,
        params.toString()
    );
}

저는 우리가 가지고 있는 모든 노선에 대해 하나의 구성 요소만 사용하는 흥미로운 상황을 겪었습니다.경로는 다음과 같습니다.

const routes: Routes = [
  {
    path: '',
    component: HomeComponent,
    children: [
      { path: 'companies', component: HomeComponent },
      { path: 'pipeline', component: HomeComponent },
      // ...
    ]
  },
  // ...
];

그래서 기본적으로 경로는/,/companies그리고./pipeline모두 로드해야 하는 동일한 구성 요소를 가지고 있었습니다.하기 때문에 Router Angular DOM에 있는 구성 요소의 재로드를 방지합니다navigate " 드는확약반속환했니다습을는인되메항소상"로 해결된 했습니다.null.

이것을 피하기 위해, 저는 사용해야만 했습니다.이 값을 다음으로 설정합니다.'reload'업데이트된 쿼리 문자열 매개 변수를 사용하여 라우터가 동일한 URL로 이동하도록 할 수 있었습니다.

@NgModule({
  imports: [RouterModule.forRoot(routes, { onSameUrlNavigation: 'reload' })],
  exports: [RouterModule]
})

또한 다음과 같은 BehaviorSubject를 추가할 수 있습니다.

refresher$ = new BehaviorSubject(null);

코드를 변경했습니다.

this.route.queryParamMap.subscribe(some code)

대상:

combineLatest([
    this.route.queryParamMap,
    this.refresher$
])
  .pipe(
     map((data) => data[0])
  )
  .subscribe(here is your the same code)

구독을 새로 고쳐야 할 때는 다음을 호출해야 합니다.

this.refresher$.next(null);

또한 tongOnDestroy에서 구독 취소를 추가하는 것도 잊지 마십시오.

언급URL : https://stackoverflow.com/questions/43698032/angular-how-to-update-queryparams-without-changing-route

반응형