无法在 routerOnActivate 上获取查询参数 [英] Cannot get query Params on routerOnActivate
问题描述
我在尝试使用新的 Route 库获取查询参数时遇到问题.
Im having problems trying to get query params using the new Route library.
版本2.0.0-rc.1
问题
routerOnActivate(curr:RouteSegment, prev?:RouteSegment, currTree?:RouteTree, prevTree?:RouteTree):void {
console.log(curr.getParam("test"));
}
总是打印 undefined
另一个问题是我的网址每次都被重置"(这就是为什么我认为 curr.getParam("test") 返回 undefined)
这是我的应用程序组件和我的主页组件:
Here is my App Component and My Home Component :
应用组件
import {Component} from '@angular/core';
import { Routes, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, Router } from '@angular/router'
import { HomeComponent } from './home.component';
@Component({
selector : 'my-app',
template : '<router-outlet></router-outlet>',
directives : [ ROUTER_DIRECTIVES ],
providers : [ ROUTER_PROVIDERS ]
})
@Routes([
{
path : '/',
component : HomeComponent
}
])
export class AppComponent {
constructor (private _router : Router) {
}
}
家庭组件
import { Component } from '@angular/core';
import { Router, OnActivate, RouteSegment } from '@angular/router';
@Component({
selector: 'home',
template: '<h3>THIS IS HOME</h3>'
})
export class HomeComponent implements OnActivate{
constructor(private _router : Router) {
console.log('Called');
}
routerOnActivate(curr:RouteSegment):void {
console.log(curr.getParam("test"));
}
}
测试网址
localhost:3000/?test=helloworld --> 更改为(问题)localhost:3000
localhost:3000/?test=helloworld --> Changes to(problem) localhost:3000
有人可以帮忙吗?
推荐答案
你的代码看起来不错,唯一的问题是根据 Angular 2 官方文档:
Your code looks good, the only problem is that as per official Angular 2 documentation:
查询字符串参数不再以?"分隔和&".它们由分号 (;) 分隔 这是 矩阵 URL 符号 — 我们可能没有以前看过.矩阵 URL 表示法最初是在 1996 年的提案中提出的一个想法,虽然它从未进入 HTML 标准,但它是合法的,并且在浏览器路由系统中流行起来,作为隔离属于父路由和子路由的参数的一种方式.Angular Component Router 就是这样一个系统.
The query string parameters are no longer separated by "?" and "&". They are separated by semicolons (;) This is matrix URL notation — something we may not have seen before. Matrix URL notation is an idea first floated in a 1996 proposal and although it never made it into the HTML standard, it is legal and it became popular among browser routing systems as a way to isolate parameters belonging to parent and child routes. The Angular Component Router is such a system.
因此,您可以通过从
So you can get the value of optional parameter (test) from current RouteSegment by change your address from
本地主机:3000/?test=helloworld
localhost:3000/?test=helloworld
到
localhost:3000/;test=helloworld
这篇关于无法在 routerOnActivate 上获取查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!