gpt4 book ai didi

javascript - 无法在 routerOnActivate 上获取查询参数

转载 作者:行者123 更新时间:2023-11-30 16:05:10 25 4
gpt4 key购买 nike

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

版本2.0.0-rc.1

问题

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

总是打印 undefined

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

这是我的 App 组件和我的 Home 组件:

应用组件

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

有人可以帮忙吗?

最佳答案

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

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.


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

本地主机:3000/?test=helloworld

localhost:3000/;test=helloworld

关于javascript - 无法在 routerOnActivate 上获取查询参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37144323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com