programing

각도에서 경로 매개변수를 얻는 효율적인 방법

prostudy 2022. 3. 10. 22:45
반응형

각도에서 경로 매개변수를 얻는 효율적인 방법

어떻게 하면 라우터 옵서버블을 더 효율적으로 사용할 수 있을까?예를 들어 단일 경로 파라미터를 로드해야 하는 경우(우리에게는 다음과 같은 경로가 있다고 가정해 보자./some-resource/:id)) 라우터 이벤트에 가입하고, 그 다음에 라우트 매개 변수에 가입해야 값을 얻을 수 있다.이것은 2개의 구독과 2개의 구독 취소를 필요로 한다.

다음이 필요함:

  • 보일러 판 코드 감소
  • 코드를 더 읽기 쉽게 만들기
  • 구독 제거

샘플

export class SomeComponent implements OnInit, OnDestroy {
  private routerSub: Subscription;
  private routeSub: Subscription;

  someResource: Observable<SomeResourceType>;

  constructor(private someService: SomeService,
              private route: ActivatedRoute,
              private router: Router) {
    this.routerSub = this.router.events.subscribe((event) => {
      if (event instanceof NavigationEnd) {
        this.routeSub = this.route.params.subscribe((params) => {
          if (params['id']) {
            this.someResource = this.someService.findById(params['id']);
            // will access the resource using async pipe later
          }
        });
      }
    });
  }

  ngOnInit(): void {
  }

  ngOnDestroy(): void {
    this.routerSub.unsubscribe();
    this.routeSub.unsubscribe();
  }
}

어떤 이유로 구성 요소가 각도에 의해 파괴되지 않고 다른 경로 매개변수 스택블리츠 예: https://stackblitz.com/edit/angular-router-basic-example-695kpb를 사용하여 여전히 로드되는 경우, 이벤트 구독은 데이터를 새로 고치는 데 필요하다.

활성화된 경로를 사용하면 된다.

constructor(route: ActivatedRoute) {
    this.id$ = route.params
        .pipe(pluck('id'));
}

너는 용기를 사용할 수 있다. pluck('id')기본적으로 와 같다.map(value => value.id). 스트림이 없는 것이 아니라 실제의 가치를 갖고 싶다면, 똑같이 하고 가입하면 된다.하지만 만약 그렇게 한다면, 관찰할 수 있는 것에 대한 구독을 취소하는 것을 잊지 말아라.교환원까지 테이크아웃으로 할 수 있다.

id;
private _destroyed$ = new Subject<any>();

constructor(route: ActivatedRoute) {
    route.params
        .pipe(
            takeUntil(this._destroyed$),
            pluck('id')
        ).subscribe(id => this.id = id);
}

ngOnDestroy() {
    this._destroyed$.next();
    this._destroyed$.complete();
}

다음을 시도해 보십시오.

constructor(private route: ActivatedRoute) {}

ngOnInit() {
    const id = this.route.snapshot.params['id'];
}

아무도 더 나은 해결책을 올리지 않는 한, 여기 내 것이 있다.

나는 a를 정의했다.RouterHelperService이 과정을 좀 더 쉽게 만들 수 있지한 가지 문제점은, 만약 당신이 그 주사기를 주입하려고 한다면,ActivatedRoute서비스에서 직접 인스턴스(instance)를 사용하면 매개 변수가 누락되므로 구성 요소에서 서비스로 매개 변수를 전달해야 한다.

import { Injectable } from '@angular/core';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import { filter, flatMap, map } from 'rxjs/operators';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class RouterHelperService {

  constructor(private router: Router) {
  }

  onNavigationEndReadParamByKey(route: ActivatedRoute, key: string): Observable<string> {
    return this.router.events.pipe(
      filter(event => event instanceof NavigationEnd),
      flatMap(() => {
        return route.params.pipe(
          filter(params => params[key]),
          map(params => params[key])
        );
      })
    );
  }
}

이렇게 하면 내 컴포넌트에서는 전화 한 통과 가입 한 번으로 부를 수 있다.

export class SomeComponent implements OnInit, OnDestroy {
  private routeSub: Subscription;

  someResource: Observable<SomeResourceType>;

  constructor(private someService: SomeService,
              private route: ActivatedRoute) {
     this.routeSub = this.routerHelper.onNavigationEndReadParamByKey(this.route, 'id').subscribe((id) => {
        this.someResource = this.someService.findById(+id); //+id to convert it from a string to a number
     });
  }

  ngOnInit(): void {
  }

  ngOnDestroy(): void {
    this.routeSub.unsubscribe();
  }
}

구성 요소 다시 로드를 지원하지 않는 가장 빠른 방법:

constructor(
  route: ActivatedRoute,
) {
  const myParam = route.snapshot.params.idThread;
}

구성 요소 다시 로드를 지원하는 paramMap 및 'new' RxJs 구문 사용:

constructor(
  route: ActivatedRoute,
) {
  route.paramMap.subscribe({
    next: params => {
      const myParam = params.get('myParam');
    }
  });
}

NB: 이 경우 스크리브 취소는 필수 사항이 아니며 메모리 누수로 이어지지 않아야 함

참조URL: https://stackoverflow.com/questions/52419658/efficient-way-to-get-route-parameter-in-angular

반응형