programing

Angular(최신까지 2개 이상)를 사용하여 URL에서 ID 추출

iphone6s 2023. 9. 24. 12:33
반응형

Angular(최신까지 2개 이상)를 사용하여 URL에서 ID 추출

안녕하세요 저는 Angular2를 이용하여 URL의 id 부분을 추출하려고 합니다.

http://localhost:3000/item/187809

저는 계속 장난을 치고 있습니다.ActiveRoute이내에onInit운이 없으면

     this.route.queryParams.forEach((params: any) => {
       console.log("QUERYPARAMS");
       console.log(params);
     });

나도 이렇게 노선변경 가입을 시도했습니다.

    this.routeSub = this.route.queryParams.subscribe(params => {
       console.log(params);
       console.log(+params['id']);
    }); 

그렇지만params그냥 빈 개체일 뿐입니다.

나는 이 경로를 이렇게 게으른 경로로 정의하고 있습니다.

    {
        path: item',
        children: [
           { path: ':id', loadChildren: './item/item.module#ItemModule'},
        ]
    },

문제는 게으른 로드된 루티드 차일드를 잡아주는 헤더 구성요소와 메인 구성요소가 있다는 것입니다.나는 헤더 구성요소 안에 id를 로드하려고 합니다.

뭐가 빠졌는지 알아요?

경로 매개변수 가입 및 가입 취소

  1. 다음과 같은 매개 변수가 예상되는 경로를 구성했는지 확인합니다.
{path: 'item/:id', component: SomeItemComponent}
  1. 경로 가입에 대한 변수를 선언합니다.ActiveRoute(ActiveRoute)를 가져와 구성 요소 생성기에 주입합니다.
private routeSub: Subscription;
constructor(private route: ActivatedRoute) { }
  1. ngOnInit 내부의 동일한 구성 요소에서 데이터에 액세스할 수 있습니다.params다음과 같이 구독하면 관찰할 수 있습니다.
ngOnInit() {
  this.routeSub = this.route.params.subscribe(params => {
    console.log(params) //log the entire params object
    console.log(params['id']) //log the value of id
  });
}
  1. ngOnDestroy 내부에서 메모리 누수를 방지하기 위해 구독 취소.
ngOnDestroy() {
  this.routeSub.unsubscribe();
}

업데이트 - 2021년 1월

사이에 큰 차이가 있습니다.route.params그리고.route.queryParams.

route.params, 를 구독하면 경로로 탐색할 때 제공되는 키(경로 파라미터에서 가져온 것, 1단계 참조)와 문자열 값이 포함된 개체를 반환합니다.예를 들어,

example.com/item/1

{
  itemId: '1'
}

route.queryParams, 를 구독하면 URL의 쿼리 문자열(wiki)에서 가져온 키와 문자열 값을 가진 개체를 반환합니다. 예:

example.com/welcome?var1=abc&var2=cde

{
  var1: 'abc',
  var2: 'cde'
}

route.queryParams될 것이다undefined질의 문자열이 URL에 존재하지 않는 경우. OP, 댓글에 있는 일부 사용자들이 실수로 대신 이것을 사용한 것으로 생각합니다.route.params.

답장이 조금 늦었지만 혹시라도 문제가 있으실지 모르니 앵글 설명서를 한 번 봐주시기 바랍니다.

각도 라우팅 튜토리얼

링크에서 예제를 봅니다.

ActivatedRoute 가져오기로 시작합니다.

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

그다음에 시공자에게 주입합니다.

    constructor(private route: ActivatedRoute) {}

그리고 OnInit()에서

    ngOnInit(): void {
        const id = this.route.snapshot.paramMap.get('id');
    }

이와 같이 관찰 가능한 것에 대해 직접적으로 걱정할 필요가 없습니다.

도움이 되길 바랍니다.

문제는 당신이 사용하고 있는queryParams만이 아니라params.

params: 경로에 특정한 필수 및 선택적 매개변수를 포함하는 Observable입니다.

쿼리Params:모든 경로에서 사용 가능한 쿼리 매개 변수가 들어 있는 Observable입니다.

그래서 이렇게 해보세요.

    this.route.params.subscribe(params => {
       console.log(params);
       console.log(+params['id']);
    });

여러 옵션을 선택할 수 있습니다.id

    constructor(private route: ActivatedRoute) { }

1-의 도움으로 params

    const id= this.route.snapshot.params['id'];

아니면

    const id = this.route.snapshot.params.id // any param name after "params"

2-의 도움으로 paramMap

    const id= this.route.snapshot.paramMap.get('id')

3-subscribe.params 해제를 )오

      private subscription: Subscription

      constructor(private route: ActivatedRoute) { }
      ngOnInit(): void {
        this.subscription = this.route.params.subscribe(params => {
          const id = params['id']
        })
      }

     //To prevent memory leak
      ngOnDestroy(): void {
        if (this.subscription)
          this.subscription.unsubscribe()
      }

업데이트됨

Imagine, you have the following route:
    {
      path: "",
      component: LayoutComponent,
      children: [
        {
          path: "action/:id", component: ChildComponent
        }
      ]
    }

LayoutComponent에 있고 ChildComponent의 파라미터를 가져오려면 다음 방법을 사용해야 합니다.

    this.route.children.forEach(child => {
      child.params.subscribe(params => {
          const id = params['id']
      })
    }

Angular 8로 작업하는 동안 동일한 문제에 직면하여 다음과 같은 방법으로 해결했습니다.

  1. 먼저 ActivatedRoute를 가져옵니다.
    import { ActivatedRoute } from '@angular/router';
  1. 그런 다음 생성기에 활성화된 경로 주입:
    constructor(private activatedRoute: ActivatedRoute) {}
  1. ngOnit 메서드는 이렇게 나타납니다.
    ngOnInit(){
        const id = this.activatedRoute.snapshot.paramMap.get('id');
    }

Angular 공식 문서에서 발견했습니다.

    this.routeSub = this.route.params.subscribe(params => {
       console.log(params);
       console.log(+params['id']);
    });

언급URL : https://stackoverflow.com/questions/42839074/extract-id-from-url-using-angular-2-till-latest

반응형