gpt4 book ai didi

angular - 父组件从 ActivatedRoute 获取空 Params

转载 作者:太空狗 更新时间:2023-10-29 16:54:08 25 4
gpt4 key购买 nike

我有一个主要组件,里面有一个路由器 socket 。在路由器 socket 中加载的组件中,我像这样获取 url 参数:

ngOnInit(): void {
// _route is injected ActivatedRoute
this._route.params.subscribe((params: Params) => {
if(params['url']){
this.testUrl = params['url'].replace(new RegExp('\%2[fF]', 'g'), '/');

}

});
}

这工作正常,但是当我在我的顶级组件上尝试它时,params 对象总是空的。我不明白为什么嵌套组件 param 对象中包含数据,而我试图以完全相同的方式访问它。没有错误可以继续,param 对象只是空的。

为什么我的父组件没有从 ActivatedRoute 获得正确的 Params 对象?

编辑:

作为请求的完整父组件

import { OnInit, Component, Directive } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { Observable } from 'rxjs/Observable';

@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
})
export class AppComponent {
public testUrl: string;
constructor(private router: Router, private _route: ActivatedRoute) {

}
ngOnInit(): void{
this._route.queryParams.subscribe((params: Params) => {
console.log(params);

if (params['url']) {
this.testUrl = params['url'].replace(new RegExp('\%2[fF]', 'g'), '/');
alert(params['url']);
}
});
}

}

app.module.ts 的路由器代码:

RouterModule.forRoot([
{ path: '', component: CheckMobileComponent },
{ path: '**', component: CheckMobileComponent }
]),

嵌套模块的路由代码:

RouterModule.forChild([
{ path: 'report', component: MobileReportComponent }

我的 app.component 没有直接指定的路由,因为它是由 index.html 中的选择器加载的。

最佳答案

ActivatedRoute:包含与路由导出中加载的组件关联的路由信息​​。如果您想在其外部访问路线详细信息,请使用以下代码。

import { Component } from '@angular/core';
import { Router, ActivatedRoute, Params, RoutesRecognized } from '@angular/router';

export class AppComponent {

constructor(private route: ActivatedRoute, private router: Router) {

}

ngOnInit(): void {
this.router.events.subscribe(val => {

if (val instanceof RoutesRecognized) {

console.log(val.state.root.firstChild.params);

}
});

}
}

还有其他方法可以在组件之间共享数据,例如 by using a service .

有关如何将此作为概念处理的更多详细信息,read comments here .

关于angular - 父组件从 ActivatedRoute 获取空 Params,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42947133/

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