加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – 父组件从ActivatedRoute获取空参数

发布时间:2020-12-17 08:00:46 所属栏目:安全 来源:网络整理
导读:我有一个主要组件,其中有一个路由器插座.在路由器插座中加载的组件中,我抓住url参数,如下所示: ngOnInit(): void { // _route is injected ActivatedRoute this._route.params.subscribe((params: Params) = { if(params['url']){ this.testUrl = params['u
我有一个主要组件,其中有一个路由器插座.在路由器插座中加载的组件中,我抓住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]','/');
        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,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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读