IT박스

Angular 5의 URL에서 쿼리 매개 변수를 얻는 방법은 무엇입니까?

itboxs 2020. 7. 9. 19:32
반응형

Angular 5의 URL에서 쿼리 매개 변수를 얻는 방법은 무엇입니까?


angular 5.0.3을 사용하고 있으며 많은 쿼리 매개 변수로 응용 프로그램을 시작하고 싶습니다. "/ app? param1 = hallo & param2 = 123"과 같이 angular2의 URL에서 쿼리 매개 변수를 얻는 방법에 제공된 모든 팁 은 무엇입니까? 나를 위해 작동하지 않습니다.

쿼리 매개 변수가 작동하는 방법에 대한 아이디어가 있습니까?

private getQueryParameter(key: string): string {
  const parameters = new URLSearchParams(window.location.search);
  return parameters.get(key);
}

이 개인 함수는 매개 변수를 얻는 데 도움이되지만 새로운 Angular 환경에서 올바른 방법이라고 생각하지 않습니다.

[업데이트 :] 내 주요 앱은 @Component ({...})와 같습니다. 내보내기 클래스 AppComponent는 OnInit {

  constructor(private route: ActivatedRoute) {}

  ngOnInit(): void {
    // would like to get query parameters here...
    // this.route...
  }
}

Angular 5에서는 this.route.queryParams를 구독하여 쿼리 매개 변수에 액세스합니다.

예 : "/ app? param1 = hallo & param2 = 123"

param1: string;
param2: string;
constructor(private route: ActivatedRoute) {
    console.log('Called Constructor');
    this.route.queryParams.subscribe(params => {
        this.param1 = params['param1'];
        this.param2 = params['param2'];
    });
}

반면 경로 변수는 "this.route.snapshot.params"에 의해 액세스됩니다.

예 : "/ param1 / : param1 / param2 / : param2"

param1: string;
param2: string;
constructor(private route: ActivatedRoute) {
    this.param1 = this.route.snapshot.params.param1;
    this.param2 = this.route.snapshot.params.param2;
}

이것은 나를 위해 가장 깨끗한 솔루션입니다

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

export class MyComponent {
  constructor(
    private route: ActivatedRoute
  ) {}

  ngOnInit() {
    const firstParam: string = this.route.snapshot.queryParamMap.get('firstParamKey');
    const secondParam: string = this.route.snapshot.queryParamMap.get('secondParamKey');
  }
}

OP가 Angular 5 솔루션을 요청했지만 새로운 (6+) Angular 버전에 대해이 질문을 우연히 발견 한 모든 사용자에게 OP가 있음을 알고 있습니다. ActivatedRoute.queryParams (대부분의 다른 답변은 기반)에 관한 문서 인용 :

두 가지 이전 속성을 계속 사용할 수 있습니다. 그것들은 대체 제품보다 능력떨어지고, 낙담 하며, 향후 Angular 버전에서 더 이상 사용되지 않을 수 있습니다 .

params — 경로와 관련된 필수 및 선택적 매개 변수가 포함 된 Observable입니다. 대신 paramMap을 사용하십시오.

queryParams — 모든 경로에 사용 가능한 쿼리 매개 변수가 포함 된 Observable입니다. 대신 queryParamMap을 사용하십시오.

Docs 에 따르면 쿼리 매개 변수를 얻는 간단한 방법은 다음과 같습니다.

constructor(private route: ActivatedRoute) { }

ngOnInit() {
    this.param1 = this.route.snapshot.paramMap.get('param1');
    this.param2 = this.route.snapshot.paramMap.get('param2');
}

고급 구성 요소 (예 : 고급 구성 요소 재사용)는 문서 장을 참조하십시오 .

편집하다:

아래 의견에서 올바르게 언급 했듯이이 답변은 적어도 OP에서 지정한 경우에는 잘못되었습니다.

OP는 전역 쿼리 매개 변수 (/ app? param1 = hallo & param2 = 123)를 요청합니다. 이 경우 queryParamMap을 사용해야합니다 (@ dapperdan1985 답변과 동일).

반면에 paramMap은 경로에 특정한 매개 변수에 사용됩니다 (예 : / app / : param1 / : param2, 결과적으로 / app / hallo / 123).

@JasonRoyle과 @daka에게 감사의 말을 전합니다.


다음 과 같은 HttpParams를 사용할 수도 있습니다 .

  getParamValueQueryString( paramName ) {
    const url = window.location.href;
    let paramValue;
    if (url.includes('?')) {
      const httpParams = new HttpParams({ fromString: url.split('?')[1] });
      paramValue = httpParams.get(paramName);
    }
    return paramValue;
  }

import { ParamMap, Router, ActivatedRoute } from '@angular/router';

constructor(private route: ActivatedRoute) {}

ngOnInit() {
    console.log(this.route.snapshot.queryParamMap);
}

최신 정보

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

export class LoginComponent {
    constructor(private router: Router) {
        const snapshot: RouterStateSnapshot = router.routerState.snapshot;
        console.log(snapshot);  // <-- hope it helps
    }
}

나를위한 작업 :

constructor(private route: ActivatedRoute) {}

ngOnInit()
{
    this.route.queryParams.subscribe(map => map);
    this.route.snapshot.queryParams; 
}

더 많은 옵션을 볼 angular2에 URL에서 어떻게 GET 쿼리 PARAMS를?


Stumbled across this question when I was looking for a similar solution but I didn't need anything like full application level routing or more imported modules.

The following code works great for my use and requires no additional modules or imports.

  GetParam(name){
    const results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if(!results){
      return 0;
    }
    return results[1] || 0;
  }

  PrintParams() {
    console.log('param1 = ' + this.GetParam('param1'));
    console.log('param2 = ' + this.GetParam('param2'));
  }

http://localhost:4200/?param1=hello&param2=123 outputs:

param1 = hello
param2 = 123

When you have an empty route object, it's mainly due to the fact that you are not using a router-outlet in your app.component.html.

Without this, you won't be able to get a meaningful route object with non empty subObjects, particularly params & queryParams.

Try to add <router-outlet><router-outlet>just before calling your <app-main-component></app-main-component>

Before that, make sure you have your query param ready in app-routing > which export the class Route used by App component :

param: '/param/:dynamicParam', path: MyMainComponent

Last thing of course, to get your param, I personnaly use this.route.snapshot.params.dynamicParam where dynamicParam is the name used in your app-routing component :)


Be careful with your routes. A "redirectTo" will remove|drop any query parameter.

const appRoutes: Routes [
 {path: "one", component: PageOneComponent},
 {path: "two", component: PageTwoComponent},
 {path: "", redirectTo: "/one", pathMatch: full},
 {path: "**", redirectTo: "/two"}
]

I called my main component with query parameters like "/main?param1=a&param2=b and assume that my query parameters arrive in the "ngOnInit()" method in the main component before the redirect forwarding takes effect.

But this is wrong. The redirect will came before, drop the query parameters away and call the ngOnInit() method in the main component without query parameters.

I changed the third line of my routes to

{path: "", component: PageOneComponent},

and now my query parameters are accessible in the main components ngOnInit and also in the PageOneComponent.


Found in: Parent components gets empty Params from ActivatedRoute

Worked for me:

import {Component, OnDestroy, OnInit} from '@angular/core';
import { Router, ActivatedRoute, Params, RoutesRecognized } from '@angular/router';

@Component({
  selector: 'app-navigation-bar',
  templateUrl: './navigation-bar.component.html',
  styleUrls: ['./navigation-bar.component.scss']
})
export class NavigationBarComponent implements OnInit, OnDestroy {
  private sub: any;
  constructor(private route: ActivatedRoute, private router: Router) {}

  ngOnInit() {
    this.sub = this.router.events.subscribe(val => {
      if (val instanceof RoutesRecognized) {
        console.log(val.state.root.firstChild.params);
      }
    });
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }

}

Just stumbled upon the same problem and most answers here seem to only solve it for Angular internal routing, and then some of them for route parameters which is not the same as request parameters.

I am guessing that I have a similar use case to the original question by Lars.

For me the use case is e.g. referral tracking:

Angular running on mycoolpage.com, with hash routing, so mycoolpage.com redirects to mycoolpage.com/#/. For referral, however, a link such as mycoolpage.com?referrer=foo should also be usable. Unfortunately, Angular immediately strips the request parameters, going directly to mycoolpage.com/#/.

Any kind of 'trick' with using an empty component + AuthGuard and getting queryParams or queryParamMap did, unfortunately, not work for me. They were always empty.

My hacky solution ended up being to handle this in a small script in index.html which gets the full URL, with request parameters. I then get the request param value via string manipulation and set it on window object. A separate service then handles getting the id from the window object.

index.html script

const paramIndex = window.location.href.indexOf('referrer=');
if (!window.myRef && paramIndex > 0) {
  let param = window.location.href.substring(paramIndex);
  param = param.split('&')[0];
  param = param.substr(param.indexOf('=')+1);
  window.myRef = param;
}

Service

declare var window: any;

@Injectable()
export class ReferrerService {

  getReferrerId() {
    if (window.myRef) {
      return window.myRef;
    }
    return null;
  }
}

If you're not using Angular router try, querystring. Install it

npm install --save querystring

to your project. In your component do something like this

import * as qs from 'querystring';
...
ngOnInit() {
   const params = qs.parse(window.location.search.substring(1));
   ...
}

The substring(1) is necessary because if you have something like this '/mypage?foo=bar' then the key name for will be ?foo

참고URL : https://stackoverflow.com/questions/47455734/how-to-get-query-parameters-from-url-in-angular-5

반응형