IT story

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

hot-time 2020. 4. 30. 07:37
반응형

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


angular2.0.0-beta.7을 사용합니다. 구성 요소가 경로에로드되면 구성 요소가로 경로 /path?query=value1재 지정됩니다 /path. GET 매개 변수가 제거 된 이유는 무엇입니까? 매개 변수를 어떻게 보존 할 수 있습니까?

라우터에 오류가 있습니다. 내가 같은 주요 경로가 있다면

@RouteConfig([
  {
      path: '/todos/...',
      name: 'TodoMain',
      component: TodoMainComponent
  }
])

우리 아이는

@RouteConfig([
  { path: '/', component: TodoListComponent, name: 'TodoList', useAsDefault:true },
  { path: '/:id', component: TodoDetailComponent, name:'TodoDetail' }
])

그런 다음 TodoListComponent에서 매개 변수를 얻을 수 없습니다. 나는 얻을 수있다

params("/my/path;param1=value1;param2=value2") 

그러나 나는 고전을 원한다

query params("/my/path?param1=value1&param2=value2")

ActivatedRoute하나 의 인스턴스를 주입하면 a queryParamsobservable을 포함한 다양한 observable을 구독 할 수 있습니다 params.

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

@Component({...})
export class MyComponent implements OnInit {

  constructor(private activatedRoute: ActivatedRoute) {}

  ngOnInit() {
    // Note: Below 'queryParams' can be replaced with 'params' depending on your requirements
    this.activatedRoute.queryParams.subscribe(params => {
        const userId = params['userId'];
        console.log(userId);
      });
  }

}

구독 취소에 대한 참고 사항

@Reto와 @ codef0rmer는 공식 문서에 unsubscribe()따르면 구성 요소 내부 onDestroy()메소드가 필요하지 않다는 것을 올바르게 지적했습니다 . 이것은 내 코드 샘플에서 제거되었습니다. ( 자습서의 파란색 경고 상자 참조 )


http://stackoverflow.com?param1=value 같은 URL

다음 코드로 param1을 얻을 수 있습니다.

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

@Component({
    selector: '',
    templateUrl: './abc.html',
    styleUrls: ['./abc.less']
})
export class AbcComponent implements OnInit {
    constructor(private route: ActivatedRoute) { }

    ngOnInit() {
        // get param
        let param1 = this.route.snapshot.queryParams["param1"];
    }
}

질문에 버전 7지정되었지만 이 질문은 Google에서 각도 2 검색어 매개 변수 와 같은 일반적인 문구에 대한 최상위 검색 결과로 나타납니다 . 이러한 이유로 최신 라우터에 대한 답변이 있습니다 (현재는 alpha.7 ).

매개 변수를 읽는 방식이 크게 바뀌 었습니다. 먼저 다음 Router과 같이 생성자 매개 변수에서 호출 종속성을 주입해야합니다 .

constructor(private router: Router) { }

그런 다음 ngOnInit메소드 에서 쿼리 매개 변수를 구독 할 수 있습니다 (생성자도 괜찮지 만 ngOnInit테스트 가능성에 사용해야 함).

this.router
  .routerState
  .queryParams
  .subscribe(params => {
    this.selectedId = +params['id'];
  });

이 예에서는 URL과 같은 검색어 매개 변수 ID읽습니다 example.com?id=41.

여전히 주목할 사항이 몇 가지 있습니다.

  1. paramslike의 속성에 액세스 하면 params['id']항상 문자열반환 되며 앞에 접두사를 붙여 숫자 로 변환 할 수 있습니다 +.
  2. The reason why the query params are fetched with observable is that it allows re-using the same component instance instead of loading a new one. Each time query param is changed, it will cause a new event that we have subscribed for and thus we can react on changes accordingly.

I really liked @StevePaul's answer but we can do the same without extraneous subscribe/unsubscribe call.

import { ActivatedRoute } from '@angular/router';
constructor(private activatedRoute: ActivatedRoute) {
    let params: any = this.activatedRoute.snapshot.params;
    console.log(params.id);
    // or shortcut Type Casting
    // (<any> this.activatedRoute.snapshot.params).id
}

To send query params

import { Router } from '@angular/router';
this.router.navigate([ '/your-route' ], { queryParams: { key: va1, keyN: valN } });

To receive query params

import { ActivatedRoute } from '@angular/router';
this.activatedRoute.queryParams.subscribe(params => {
    let value_1 = params['key'];
    let value_N = params['keyN'];
});

Official source


Hi you can use URLSearchParams, you can read more about it here.

import:

import {URLSearchParams} from "@angular/http";

and function:

getParam(){
  let params = new URLSearchParams(window.location.search);
  let someParam = params.get('someParam');
  return someParam;
}

Notice: It's not supported by all platforms and seems to be in "EXPERIMENTAL" state by angular docs


First off, what I have found working with Angular2 is that the url with a query string would be /path;query=value1

To access it in a component you use So is this, but now follows a code block:

    constructor(params: RouteParams){
    var val = params.get("query");
    }

As to why it would be removed when you load the component, that isn't default behavior. I checked specificly in a clean test project and wasn't redirected or changed. Is it a default route or something else that is special about the routing?

Read about routing with query strings and params in the Angular2 Tutorial at https://angular.io/docs/ts/latest/guide/router.html#!#query-parameters


You can get the query parameters when passed in URL using ActivatedRoute as stated below:-

url:- http:/domain.com?test=abc

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

@Component({
  selector: 'my-home'
})
export class HomeComponent {

  constructor(private sharedServices : SharedService,private route: ActivatedRoute) { 
    route.queryParams.subscribe(
      data => console.log('queryParams', data['test']));
  }

}

Get URL param as an object.

import { Router } from '@angular/router';
constructor(private router: Router) {
    console.log(router.parseUrl(router.url));
}

If you only want to get query parameter once, the best way is to use take method so you do not need to worry about unsubscription. Here is the simple snippet:-

constructor(private route: ActivatedRoute) {
  route.snapshot.queryParamMap.take(1).subscribe(params => {
     let category = params.get('category')
     console.log(category);
  })
}

Note: Remove take(1) if you want to use parameter values in future.


now it is:

this.activatedRoute.queryParams.subscribe((params: Params) => {
  console.log(params);
});

I hope it will help someone else.

Question above states that query param value is needed after page has been redirected and we can assume that snapshot value (the no-observable alternative) would be sufficient.

No one here mentioned about snapshot.paramMap.get from the official documentation.

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

So before sending it add this in sending/re-directing component:

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

then re-direct as either (documented here):

this.router.navigate(['/heroes', { id: heroId, foo: 'foo' }]);

or simply:

this.router.navigate(['/heroes', heroId ]);

Make sure you have added this in your routing module as documented here:

 { path: 'hero/:id', component: HeroDetailComponent }

And finally, in your component which needs to use the query param

  • add imports (documented here):

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

( documentation also imports switchMap and also injects Router and HeroService - but they are needed for observable alternative only - they are NOT needed when you use snapshot alternative as in our case ):

    constructor(
      private route: ActivatedRoute
    ) {}
  • and get the value you need ( documented here):

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

NOTE: IF YOU ADD ROUTING-MODULE TO A FEATURE MODULE (AS SHOWN IN DOCUMENTATION) MAKE SURE THAT IN APP.MODULE.ts THAT ROUTING MODULE COMES BEFORE AppRoutingModule (or other file with root-level app routes) IN IMPORTS: [] . OTHERWISE FEATURE ROUTES WILL NOT BE FOUND (AS THEY WOULD COME AFTER { path: '**', redirectTo: '/not-found' } and you would see only not-found message).


You just need to inject ActivatedRoute in constructor and then just access params or queryParams over it

constructor(private route:ActivatedRoute){}
ngOnInit(){
        this.route.queryParams.subscribe(params=>{
        let username=params['username'];
      });
 }

In Some cases it doesn't give anything in NgOnInit ...maybe because of init call before initialization of params in this case you can achieve this by asking observable to wait for some time by function debounceTime(1000)

e.g=>

 constructor(private route:ActivatedRoute){}
    ngOnInit(){
            this.route.queryParams.debounceTime(100).subscribe(params=>{
            let username=params['username'];
          });
     }

debounceTime() Emits a value from source observable only after particular time span passed without another source emission


You cannot get a parameter from the RouterState if it's not defined in the route, so in your example, you have to parse the querystring...

Here is the code I used:

let re = /[?&]([^=#&]+)=([^&#]*)/g;
let match;
let isMatch = true;
let matches = [];
while (isMatch) {
    match = re.exec(window.location.href);
    if (match !== null) {
        matches[decodeURIComponent(match[1])] = decodeURIComponent(match[2]);
        if (match.index === re.lastIndex) {
            re.lastIndex++;
        }
    }
    else {
        isMatch = false;
    }
}
console.log(matches);


A variation on Steve Paul's solution, I prefer to avoid unnecessary ivars, so to remove the need for the unsubscribe() call during ngOnDestroy, just subscribe to the observable with take(1) and it will be automatically released after the first value - preventing memory leaks

import 'rxjs/add/operator/take';
import {Router, ActivatedRoute} from '@angular/router';

@Component({...})
export class MyComponent implements OnInit {

  constructor(private activatedRoute: ActivatedRoute) {
    this.activatedRoute.params.take(1).subscribe((params: any) => {
      let userId = params['userId'];
      console.log(userId);
    });
  }

}

참고URL : https://stackoverflow.com/questions/35688084/how-to-get-query-params-from-url-in-angular-2

반응형