问题描述
我正在尝试从rc1迁移到rc4,但是我无法获取查询字符串参数. ActivatedRoute对象始终为空.
I am trying to migrate from rc1 to rc4 and i have trouble getting query string parameters. ActivatedRoute object always empty.
hero.component.ts
import {Component, OnInit} from "@angular/core";
import {Control} from "@angular/common";
import {ROUTER_DIRECTIVES, ActivatedRoute} from '@angular/router';
@Component({
template: '../partials/main.html',
directives: [ROUTER_DIRECTIVES]
})
export class HeroComponent implements OnInit {
constructor(private _activatedRoute: activatedRoute) {
}
ngOnInit() {
this._activatedRoute.params.subscribe(params => {
console.log(params);
});
}
}
main.ts
import {bootstrap} from '@angular/platform-browser-dynamic';
import {HTTP_PROVIDERS, RequestOptions, Http} from '@angular/http';
import {AppRouterProviders} from './app.routes';
bootstrap(AppComponent, [
AppRouterProviders,
HTTP_PROVIDERS
]);
app.component.ts
import {Component, OnInit} from '@angular/core';
import {HeroComponent} from './hero.component';
import {RouteConfig, Router, ROUTER_DIRECTIVES} from '@angular/router';
@Component({
selector: 'my-app',
templateUrl: '../partials/main.html',
directives: [
HeroComponent,
ROUTER_DIRECTIVES
]
})
export class AppComponent {
}
partials/main.html
<a class="nav-link" [routerLink]="['/']" [queryParams]="{st: 'new'}">New</a>
app.routes.ts
import {provideRouter, RouterConfig} from '@angular/router';
import {HeroComponent} from './hero.component';
import {ErrorComponent} from './error.component';
const routes: RouterConfig = [
{path:'', component: HeroComponent},
{path:'**', component: ErrorComponent}
];
export const AppRouterProviders = [
provideRouter(routes)
];
当我单击链接时,新建"控制台将打印出空对象
When i click on link 'New' console prints out empty object
已更新
推荐答案
更新(最终版本2.0.0)
(somepath/:someparam/someotherpath
),您可以使用_router.queryParams.subscribe(...)
订阅它们:
(somepath/:someparam/someotherpath
) you can subscribe to them using _router.queryParams.subscribe(...)
:
export class HeroComponent implements OnInit {
constructor(private _activatedRoute: ActivatedRoute, private _router:Router) {
_activatedRoute.queryParams.subscribe(
params => console.log('queryParams', params['st']));
原始
如果要使用queryParams
代替路由参数(somepath/:someparam/someotherpath
),则可以使用_router.routerState.queryParams.subscribe(...)
订阅它们:
If you want queryParams
instead of route params (somepath/:someparam/someotherpath
) you can subscribe to them using _router.routerState.queryParams.subscribe(...)
:
export class HeroComponent implements OnInit {
constructor(private _activatedRoute: ActivatedRoute, private _router:Router) {
_router.routerState.queryParams.subscribe(
params => console.log('queryParams', params['st']));
这篇关于获取路线查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!