我有完全相同的情況,我發現it's too late訂閱子元件的構造函數中的NavigationEnd和Pairwise。
你可以通過像下圖所示的服務訂閱路由器在你的根組件和共享路線數據:
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