私はまったく同じシナリオを持ちましたが、子コンポーネントのコンストラクタでpairwiseを使用してNavigationEndをサブスクライブすると、it's too lateが見つかりました。
あなたのルート要素でルータに加入し、次の例のようなサービスを通じてルートデータを共有することができます:
events.service.ts
import { Injectable } from '@angular/core';
import { RouteChanged } from '../models/route-changed.model';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class EventsService {
public routeChanged = new BehaviorSubject<RouteChanged>({ prevRoute: '/', currentRoute: '/' });
constructor() {
}
}
app.component.ts(あなたをルートコンポーネント)
...
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
private subscriptions = new Subscription();
constructor(private eventsService: EventsService) {
this.subscriptions.add(this.router.events
.filter(event => event instanceof NavigationEnd)
.pairwise()
.subscribe(navigationEvents => {
const prevPage = <NavigationEnd>navigationEvents[0];
const currentPage = <NavigationEnd>navigationEvents[1];
this.eventsService.routeChanged.next(
{ prevRoute: prevPage.urlAfterRedirects, currentRoute: currentPage.urlAfterRedirects });
}));
}
ngOnDestroy(): void {
this.subscriptions.unsubscribe();
}
...
}
あなたのターゲット-route.ts
...
constructor(private eventsService: EventsService) {
this.subscriptions.add(this.eventsService.routeChanged.subscribe((routeChanged) => {
// use routeChanged.prevRoute and routeChanged.currentRoute here...
}));
}
P.S.子コンポーネントがページの読み込み後にサブスクライブする場合は、適切な以前のルートイベントを取得するために、サービス内にBehaviorSubjectまたはReplaySubjectを使用することが重要です。
実際には、ルートコンポーネントのサービスまたは少なくともハンドラが必要です。 – lexith