从 Angular 中的 URL 获取路由器状态

Get router state from URL in Angular

使用路由器事件我可以看到导航更改和更新 URL。但是如何从 URL 中获取实际的路由器状态(数据、解析、参数等)。我尝试使用 ActivatedRoute 但这只会在组件初始化后初始化。

当前代码:

@Component({...})
export class SecundaryMenuComponent implements OnInit, OnDestroy {
  private titleSubject$: BehaviorSubject<string> = new BehaviorSubject<string>('');
  public title$: Observable<string> = this.titleSubject$.asObservable();

  private navSubscription: Subscription;

  constructor(private router: Router, private activeRoute: ActivatedRoute) {
    this.navSubscription = this.router.events.subscribe((event: NavigationEvent) => {
      this.handleRoutingEvent(event);
    });
  }

  ngOnInit(): void {}

  ngOnDestroy(): void {
    this.navSubscription.unsubscribe();
  }

  handleRoutingEvent(event: NavigationEvent) {
    if (event instanceof NavigationEnd) {
      this.titleSubject$.next(event.urlAfterRedirects);
    }
  }
}

那么如何在 handleRoutingEvent 函数中访问活动路由器状态?

你可以试试这个:

@Component({templateUrl:'template.html'})
class MyComponent {
  constructor(router: Router) {
    const state: RouterState = router.routerState;
    const root: ActivatedRoute = state.root;
    const child = root.firstChild;
    const id: Observable<string> = child.params.map(p => p.id);
    //...
  }
}

经过更多搜索,我找到了 this 并将我的代码更改为以下内容:

@Component({...})
export class SecundaryMenuComponent implements OnInit, OnDestroy {
  private titleSubject$: BehaviorSubject<string> = new BehaviorSubject<string>('');
  public title$: Observable<string> = this.titleSubject$.asObservable();

  private routeUrl$: Observable<UrlSegment[]>;
  private routeUrlSubscription: Subscription;

  constructor(private router: Router, private route: ActivatedRoute) {
    this.routeUrl$ = this.router.events.pipe(
      filter((event) => event instanceof NavigationEnd),
      switchMap(() => {
        const url = this.route.firstChild?.url;
        return url || of();
      })
    );

    this.routeUrlSubscription = this.routeUrl$.subscribe((url) => this.handleRouteUrl(url));
  }

  ngOnInit(): void {}

  ngOnDestroy(): void {
    this.routeUrlSubscription.unsubscribe();
  }

  handleRouteUrl(url: UrlSegment[]) {
    let routeUrl = '/' + url.join('/');
    this.titleSubject$.next(routeUrl);
  }
}

现在我根据实际的路由器数据而不是事件 URL 获得了正确的标题。同样的原理也可以用来获取参数、数据等