父组件从ActivatedRoute

时间:2017-03-22 09:14:56

标签: angular typescript

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

5 个答案:

答案 0 :(得分:30)

Assert.assertEquals(actual,expected); :包含与路由器插座中加载的组件关联的路由的信息。如果您想访问其外的路线详细信息,请使用以下代码。

ActivatedRoute

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

有关如何将此作为概念解决的详细信息,read comments here

答案 1 :(得分:9)

非常简单的答案

    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 :(得分:4)

如果您想通过服务访问路由器参数,则此方法将无效!考虑使用服务来防止复制“路由参数值提取逻辑”(来自此Medium article):

@Injectable({
  providedIn: 'root'
})
export class MyParamsAwareService {
  constructor(private router: Router) { 
    this.router.events
      .pipe(
        filter(e => (e instanceof ActivationEnd) && (Object.keys(e.snapshot.params).length > 0)),
        map(e => e instanceof ActivationEnd ? e.snapshot.params : {})
      )
      .subscribe(params => {
      console.log(params);
      // Do whatever you want here!!!!
      });
  }
}

答案 3 :(得分: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

答案 4 :(得分:1)

我对此有一个非常类似的问题,主要是因为我对路线的实际运作方式有误解。我以为我可以沿着路径参数链向上移动,每个路径参数都是父/子关系。但是,如果一条路由包含多个路径元素(例如/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 }

  ]   

}
相关问题