延迟加载模块上的 Angular 9 路由器事件

Véo*_*oth 5 lazy-loading angular

我正在努力处理 Angular 提供的 Router.events observable。我的应用程序有两个延迟加载的模块。每个都有一个导航菜单,显示一些在应用程序内部导航的链接。我希望我的链接之一根据当前路线显示为选定状态。

问题是,当我使用基于 router.events 可观察的可观察的异步管道时,在我的模板被 Angular 处理之前,路由事件已经被发出。

I Kknow that if I subscribe manually inside the constructor of my component, I can get the data. If I do the same inside the ngOnInit function, same as with the async pipe, there are no data emitted. It's working fine if I navigate using a link after the page is loaded.

Do you know a way on how I could achieve that ?

Thanks !

Véo*_*oth 1

我有人需要它,这就是我解决它的方法。如果您有延迟加载的模块,请确保在根组件上导入此服务,以便订阅在一开始就发生。

import {Injectable} from '@angular/core';
import {Observable, ReplaySubject} from 'rxjs';
import {filter, map, tap} from 'rxjs/operators';
import {NavigationEnd, Router} from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class RouterService {

  _events = new ReplaySubject<string>();

  constructor(private readonly router: Router) {
    router.events.pipe(
      filter(e => e instanceof NavigationEnd),
      map(e => e as NavigationEnd),
      map((e: NavigationEnd) => e.urlAfterRedirects),
      tap((url) => this._events.next(url))
    ).subscribe();
  }

  get events(): Observable<string> {
    return this._events.asObservable();
  }
}
Run Code Online (Sandbox Code Playgroud)