首页 文章

父组件从ActivatedRoute获取空参数

提问于
浏览
13

我有一个主要组件,其中有一个路由器插座 . 在路由器插座中加载的组件中,我 grab 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中的选择器加载 .

4 回答

  • 21

    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 .

  • 1

    非常简单的答案

    import { Component } from '@angular/core';
        import { Router, ActivatedRoute, Params, RoutesRecognized } from 
       '@angular/router';
    
        export class AppComponent {
    
        constructor(private actRoute: ActivatedRoute, private router: 
                     Router){}
    
       ngOnInit(): void {
         this.actRoute.firstChild.params.subscribe(
           (params: any) => {
             if (params.hasOwnProperty('<whatever the param name>') != '') {
                //do whatever you want
              } 
           }
        });
    
       }
    }
    
  • 2

    ActivatedRoute 适用于通过 router-outlet 加载的组件 . From docs - 它:

    包含与插座中加载的组件关联的路径的信息 .

    我不认为你可以在未插入插座的组件中使用它 . 它也不适用于组件扩展的基类 .

    class A { constructor(public route: ActivatedRoute) } 
    class B extends A { ngOnInit() { this.route; } }        // not working
    class C { constructor(public route: ActivatedRoute) }   // working if loaded in outlet
    
  • 8

    我遇到一个非常类似的问题主要是由于我对路线实际工作方式的误解 . 我想我可以上去路径参数链,每一个都是父/子关系 . 但是,如果路径有多个路径元素(例如 /dashboardprofile/:user_id ),则取决于您在路由模块中设置路由的方式 .

    要解释一下让我点击它的不同方式:

    // If I am trying to access ActivatedRoute from the CheckMobileComponent (say 
    // through a `router-outlet`), I could get it through something like 
    // `this._route.firstChild`
    
    { path: '', component: CheckMobileComponent, children: [
    
        // If I want to get things from the '' context in MobileReportComponent, it 
        // would be through something like `this._route.parent`
    
        { path: 'report', component: MobileReportComponent }
    
      ]   
    
    }
    

相关问题