无法在routerOnActivate上获取查询参数

时间:2016-05-10 16:38:14

标签: javascript angular angular2-routing

我在尝试使用新的Route库获取查询参数时遇到了问题。

版本 2.0.0-RC.1

问题

routerOnActivate(curr:RouteSegment, prev?:RouteSegment, currTree?:RouteTree, prevTree?:RouteTree):void {
  console.log(curr.getParam("test"));
}

始终打印未定义

另一个问题是我的网址每次都被“重置”(这就是为什么我认为curr.getParam(“test”)返回undefined)

这是我的应用程序组件和我的主页组件:

APP 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) {
    }
}

HOME COMPONENT

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 - &gt;对(问题)localhost:3000

的更改

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

您的代码看起来不错,唯一的问题是根据official Angular 2 documentation

  

查询字符串参数不再用&#34;?&#34;和&#34;&amp;&#34;。它们用分号分隔(;)这是matrix URL notation - 我们以前可能没见过的东西。 Matrix URL符号是1996年提案中首次提出的一个想法,虽然它从未进入HTML标准,但它是合法的,它在浏览器路由系统中变得流行,作为隔离属于父路由和子路由的参数的一种方式。角度组件路由器就是这样一个系统。


因此,您可以通过从

更改地址,从当前RouteSegment获取可选参数(test)的值

localhost:3000 /?test = helloworld

<强> 本地主机:3000 /;测试= HelloWorld的