Angular 2에서 쿼리 변수를 처리하는 방법
내에서 routable component
내가 가진
@RouteConfig {
{path: '/login', name: 'Login', component: LoginComponent}
}
하지만 가면 쿼리 변수를 어떻게 얻 app_url/login?token=1234
습니까?
이전 두 가지 답변을 보완하기 위해 Angular2는 라우팅 내에서 쿼리 변수와 경로 변수를 지원합니다. 에서 @RouteConfig
당신이 경로 내에서 지정된 변수를 정의하면, Angular2 경로 변수로 쿼리 변수가있는 경우를 처리합니다.
샘플을 보겠습니다.
@RouteConfig([
{ path: '/:id', component: DetailsComponent, name: 'Details'}
])
다음 navigate
과 같이 라우터 의 메서드 를 호출하면 :
this.router.navigate( [
'Details', { id: 'companyId', param1: 'value1'
}]);
다음 주소를 사용합니다 : /companyId?param1=value1
. 매개 변수를 가져 오는 방법은 쿼리 매개 변수와 경로 변수 모두에 동일합니다. 차이점은 경로 변수는 필수 매개 변수로, 쿼리 매개 변수는 선택 사항으로 볼 수있는 것입니다.
도움이 되셨기를 바랍니다.
Update : 라우터 alpha.31 http 쿼리 변수가 변경된 후 더 이상 작동하지 않습니다 ( Matrix params # 2774 ). 대신 앵귤러 라우터는 매트릭스 URL 표기법을 사용합니다.
참조 https://angular.io/docs/ts/latest/guide/router.html#!#optional-route-parameters :
한정 경로 변수는 "?" 및 "&"는 URL 쿼리에 있습니다. 세미콜론 ";"으로 구분됩니다. 이것은 매트릭스 URL 표기법입니다. 이전에는 저장되어 있습니다.
RouteParams는 이제 더 이상 사용하지 않는 방법은 다음과 같습니다.
this.router.navigate(['/login'],{ queryParams: { token:'1234'}})
그런 다음 로그인 구성 요소에서 사용할 변수를 사용할 수 있습니다.
constructor(private route: ActivatedRoute) {}
ngOnInit() {
// Capture the token if available
this.sessionId = this.route.queryParams['token']
}
다음 은 문서입니다.
RouteParams
더 이상 존재하지 않는 것은 보이며 . 매트릭스 URL 표기법 매개 변수에 대한 액세스를 제공합니다. 쿼리는 많은 변수 를 얻을 수 있습니다.
기존의 쿼리를 통해 PARAMATERS는 원하는 결과를 얻지 않습니다.
조각을 보존하는 것은 이제 라우터 3.0.0-rc.1에서 선택 사항입니다.ActivatedRoute
ActivatedRoute
?
Router.RouterState
import { Router, ActivatedRoute } from '@angular/router';
@Component ({...})
export class paramaterDemo {
private queryParamaterValue: string;
private matrixParamaterValue: string;
private querySub: any;
private matrixSub: any;
constructor(private router: Router, private route: ActivatedRoute) { }
ngOnInit() {
this.router.routerState.snapshot.queryParams["queryParamaterName"];
this.querySub = this.router.routerState.queryParams.subscribe(queryParams =>
this.queryParamaterValue = queryParams["queryParameterName"];
);
this.route.snapshot.params["matrixParameterName"];
this.route.params.subscribe(matrixParams =>
this.matrixParamterValue = matrixParams["matrixParameterName"];
);
}
ngOnDestroy() {
if (this.querySub) {
this.querySub.unsubscribe();
}
if (this.matrixSub) {
this.matrixSub.unsubscribe();
}
}
}
?
탐색시 표기법 과 표기법 을 조작 할 수 있지만 ;
매트릭스 표기법은 아직 작동하지 않습니다. plnker 최근에 사용할 수있는 문서 는 다음과 같을 것입니다.
let sessionId = 123456789;
let navigationExtras = {
queryParams: { 'session_id': sessionId },
fragment: 'anchor'
};
// Navigate to the login page with extras
this.router.navigate(['/login'], navigationExtras);
이것은 나를 위해 일했습니다 (Angular 2.1.0 기준).
constructor(private route: ActivatedRoute) {}
ngOnInit() {
// Capture the token if available
this.sessionId = this.route.snapshot.queryParams['token']
}
(/ hello-world와 같은 차일드 경로 전용)
이런 종류의 전화를하려는 경우 :
/ 안녕하세요? foo = 바 & 과일 = 바나나
Angular2는 ? 아니 & 하지만 ; 대신. 따라서 올바른 URL은 다음과 소비입니다.
/ hello-world; foo = 바; 과일 = 바나나
그리고 그 데이터를 얻으려면 :
import { Router, ActivatedRoute, Params } from '@angular/router';
private foo: string;
private fruit: string;
constructor(
private route: ActivatedRoute,
private router: Router
) {}
ngOnInit() {
this.route.params.forEach((params: Params) => {
this.foo = params['foo'];
this.fruit = params['fruit'];
});
console.log(this.foo, this.fruit); // you should get your parameters here
}
출처 : https://angular.io/docs/ts/latest/guide/router.html
Angular2 v2.1.0 (안정) :
ActivatedRoute는 구독 할 수있는 관찰 가능한 경로를 제공합니다.
constructor(
private route: ActivatedRoute
) { }
this.route.params.subscribe(params => {
let value = params[key];
});
이 경로가 업데이트 될 때마다 트리거됩니다. / 홈 / 파일 / 123-> / 홈 / 파일 / 321
각도 4 :
아래에 JS (OG 용) 및 TS 버전을 포함했습니다.
.html
<a [routerLink]="['/search', { tag: 'fish' } ]">A link</a>
위의 링크 매개 변수 배열을 사용하고 있습니다. 자세한 내용은 아래 소스를 참조하십시오.
routing.js
(function(app) {
app.routing = ng.router.RouterModule.forRoot([
{ path: '', component: indexComponent },
{ path: 'search', component: searchComponent }
]);
})(window.app || (window.app = {}));
searchComponent.js
(function(app) {
app.searchComponent =
ng.core.Component({
selector: 'search',
templateUrl: 'view/search.html'
})
.Class({
constructor: [ ng.router.Router, ng.router.ActivatedRoute, function(router, activatedRoute) {
// Pull out the params with activatedRoute...
console.log(' params', activatedRoute.snapshot.params);
// Object {tag: "fish"}
}]
}
});
})(window.app || (window.app = {}));
routing.ts (발췌)
const appRoutes: Routes = [
{ path: '', component: IndexComponent },
{ path: 'search', component: SearchComponent }
];
@NgModule({
imports: [
RouterModule.forRoot(appRoutes)
// other imports here
],
...
})
export class AppModule { }
searchComponent.ts
import 'rxjs/add/operator/switchMap';
import { OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
export class SearchComponent implements OnInit {
constructor(
private route: ActivatedRoute,
private router: Router
) {}
ngOnInit() {
this.route.params
.switchMap((params: Params) => doSomething(params['tag']))
}
더 많은 정보 :
"링크 매개 변수 배열" https://angular.io/docs/ts/latest/guide/router.html#!#link-parameters-array
"활성화 된 루트-루트 정보를위한 원 스톱 샵" https://angular.io/docs/ts/latest/guide/router.html#!#activated-route
Angular 4의 경우
URL :
http://example.com/company/100
라우터 경로 :
const routes: Routes = [
{ path: 'company/:companyId', component: CompanyDetailsComponent},
]
구성 요소:
@Component({
selector: 'company-details',
templateUrl: './company.details.component.html',
styleUrls: ['./company.component.css']
})
export class CompanyDetailsComponent{
companyId: string;
constructor(private router: Router, private route: ActivatedRoute) {
this.route.params.subscribe(params => {
this.companyId = params.companyId;
console.log('companyId :'+this.companyId);
});
}
}
콘솔 출력 :
companyId : 100
Angular2 문서 에 따르면 다음을 사용해야합니다.
@RouteConfig([
{path: '/login/:token', name: 'Login', component: LoginComponent},
])
@Component({ template: 'login: {{token}}' })
class LoginComponent{
token: string;
constructor(params: RouteParams) {
this.token = params.get('token');
}
}
Angular 5+ 업데이트
route.snapshot은 경로 매개 변수 맵의 초기 값을 제공합니다. 관찰 가능한 연산자를 구독하거나 추가하지 않고도 매개 변수에 직접 액세스 할 수 있습니다. 쓰고 읽는 것이 훨씬 간단합니다.
Angular Docs 에서 인용
당신을 위해 그것을 세분화하기 위해 다음은 새로운 라우터로 수행하는 방법입니다.
this.router.navigate(['/login'], { queryParams: { token:'1234'} });
그리고 로그인 구성 요소에서 ( 새로 .snapshot
추가 된 것을 확인하십시오 ) :
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.sessionId = this.route.snapshot.queryParams['token']
}
Angular 6에서는 다음과 같은 간단한 방법을 찾았습니다.
navigate(["/yourpage", { "someParamName": "paramValue"}]);
그런 다음 생성자 또는 ngInit
직접 사용할 수 있습니다.
let value = this.route.snapshot.params.someParamName;
Angular 7+에서이를 수행하는 간단한 방법은 다음과 가능합니다.
? -routing.module.ts에 경로를 정의하십시오.
{ path: '/yourpage', component: component-name }
구성 요소에서 ActivateRoute 및 Router 모듈을 가져 와서 생성자에 삽입합니다.
contructor(private route: ActivateRoute, private router: Router){ ... }
ngOnInit에 ActivateRoute 구독
ngOnInit() {
this.route.queryParams.subscribe(params => {
console.log(params);
// {page: '2' }
})
}
링크에 제공 :
<a [routerLink]="['/yourpage']" [queryParams]="{ page: 2 }">2</a>
참고 URL : https://stackoverflow.com/questions/34599174/how-to-handle-query-parameters-in-angular-2
'ProgramingTip' 카테고리의 다른 글
내부 조인에 대한 Entity Framework 쿼리 (0) | 2020.12.03 |
---|---|
쉘 펼쳐보기를 사용하여 지정된 패턴 목록 여러 줄을 파일에 삽입 (0) | 2020.12.03 |
C #의 다중 시작 화면? (0) | 2020.12.03 |
어떤 경우에 튜플을 사전 키로 사용합니까? (0) | 2020.12.03 |
특정에서 특정 HTTP 오류 잡기 (0) | 2020.12.03 |