【问题标题】:Cannot get query Params on routerOnActivate无法在 routerOnActivate 上获取查询参数
【发布时间】:2016-05-10 16:38:14
【问题描述】:

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

版本 2.0.0-rc.1

问题

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

总是打印 undefined

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

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

应用组件

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

有人可以帮忙吗?

【问题讨论】:

  • URL "localhost:3000/?test=helloworld" 是一个查询字符串,而不是一个路由。应该是这个“localhost:3000/test/helloworld”。
  • 我在实际应用中的参数是可选的。这就是我使用查询字符串的原因。我想我找到了问题所在。新的路由库似乎只支持矩阵 URL 表示法。所以使用 localhost:3000/;test=helloworld 而不是 "?"和“&”应该可以解决问题。我真的不喜欢这种“新”(不是新)符号,因为几乎每个站点都使用?和 &

标签: javascript angular angular2-routing


【解决方案1】:

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

查询字符串参数不再用“?”分隔和 ”&”。它们用分号 (;) 分隔,这是matrix URL notation——我们以前可能没有见过。矩阵 URL 表示法最初是在 1996 年的提案中提出的,尽管它从未成为 HTML 标准,但它是合法的,并且它在浏览器路由系统中变得流行,作为隔离属于父路由和子路由的参数的一种方式。 Angular 组件路由器就是这样一个系统。


因此,您可以通过更改您的地址从当前 RouteSegment 获取可选参数 (test) 的值

localhost:3000/?test=helloworld

localhost:3000/;test=helloworld

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-16
    • 2019-04-14
    • 2018-10-10
    • 1970-01-01
    • 1970-01-01
    • 2016-06-24
    • 2021-01-17
    • 1970-01-01
    相关资源
    最近更新 更多