网站搜索

angular - 从根组件访问活动路由参数


我需要从根组件获取活动路由器参数,以下方法不起作用

import { Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute, Event, NavigationEnd, Router, RoutesRecognized } from '@angular/router';
import { Subscription } from 'rxjs';
import { filter, map } from 'rxjs/operators'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
  title = 'frontend';
  private _owner: string
  private paramMapSub$!: Subscription

  constructor(private route: ActivatedRoute, private router: Router) {
    this._owner = ""
  }


  ngOnInit(): void {
    this.paramMapSub$ = this.router.events.pipe(
      filter(event => event instanceof NavigationEnd),
      map(() => this.route)
    ).subscribe(route => { this._owner = route.snapshot.paramMap.get("owner")! })
  }

  ngOnDestroy(): void {
    this.paramMapSub$.unsubscribe()
  }

  get owner() {
    return this._owner
  }
}

firstChild 属性始终为 null,并且活动路由从不包含任何参数。订阅 RoutesRecognized 事件也无济于事。

Angular 版本 12。