父组件从ActivatedRoute获取空参数

Gue*_*lla 22 typescript angular

我有一个主要组件,其中有一个路由器插座.在路由器插座中加载的组件中,我抓住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'), '/');

        }

    });
}
Run Code Online (Sandbox Code Playgroud)

这工作正常,但是当我在我的顶级组件上尝试它时,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']);
      }
    });
  }

}
Run Code Online (Sandbox Code Playgroud)

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

RouterModule.forRoot([
  { path: '', component: CheckMobileComponent },
  { path: '**', component: CheckMobileComponent }
]),
Run Code Online (Sandbox Code Playgroud)

嵌套模块的路由器代码:

RouterModule.forChild([
 { path: 'report', component: MobileReportComponent }
Run Code Online (Sandbox Code Playgroud)

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

Sid*_*dey 41

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);

            }
        });

    }
}
Run Code Online (Sandbox Code Playgroud)

还有其他方法可以在组件之间共享数据,例如通过使用服务.

有关如何将此作为概念解决的更多详细信息,请在此处阅读评论.


Vit*_*ati 13

非常简单的答案

    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
          } 
       }
    });

   }
}
Run Code Online (Sandbox Code Playgroud)

  • @hugoderhungrige 因为如果您不在根路由器的子组件中,这将不起作用。我目前正在处理一个令人头痛的项目,该项目在根路由中不包含标题菜单,并且撤销任何参数确实很痛苦。呃。 (2认同)

1O1*_*1O1 6

如果您想通过服务访问路由器参数,这种方法是行不通的!考虑使用服务来防止复制“路由参数值提取逻辑”(来自这篇Medium 文章):

@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!!!!
      });
  }
}
Run Code Online (Sandbox Code Playgroud)


Luc*_*gon 5

角度文档中提供了更好的解决方案。

您可以计算路由器状态中的所有参数(或数据),或者通过遍历树来获取激活组件外部的参数,RouterState如下所示

collectRouteParams(): Record<string, string> {
    let params: Record<string, string> = {};

    const stack: ActivatedRouteSnapshot[] = [
      this.router.routerState.snapshot.root,
    ];

    while (stack.length > 0) {
      const route = stack.pop();
      if (route === undefined) {
        continue;
      }

      params = { ...params, ...route.params };

      stack.push(...route.children);
    }

    return params;
  }
Run Code Online (Sandbox Code Playgroud)