我想从服务访问活动路径的元数据(导航后),但我看到的每个示例都来自组件或路线保护的观点。
我有以下设置:
路线
enum PageNames {
Dashboard = 'Dashboard',
SampleView2 = 'SampleView2'
}
const routes: Routes = [
{
path: '',
redirectTo: 'home',
pathMatch: 'full'
},
{
path: 'home',
component: HomeComponent,
data: {
name: PageNames.Dashboard
},
canActivate: [AuthGuardService]
},
{
path: 'view2',
component: SampleView2Component,
data: {
name: PageNames.SampleView2
},
canActivate: [AuthGuardService]
}
];
应用活动服务
@Injectable()
export class AppEventsService {
private _eventStream: Subject<AppEventInterface<any>>;
private eventNames: Array<string>;
constructor(private router: Router) {
this.eventNames = [];
this._eventStream = new Subject<AppEventInterface<any>>();
this.registerInternalEvents();
this.initializeSubscriptions();
}
// other member functions here
get eventStream(): Observable<AppEventInterface<any>> {
return this._eventStream.asObservable();
}
private initializeSubscriptions(): void {
this.router.events.pipe(
filter((event: Event) => event instanceof NavigationEnd)
).subscribe(() => {
this.publishEvent<RouterStateSnapshot>({
name: GlobalAppEvents.RouteChangeComplete,
type: AppEventTypes.Global,
data: this.router.routerState.snapshot
});
});
}
}
Analytics服务
@Injectable()
export class AnalyticsService {
private pageChangeEvents: Observable<AppEventInterface<RouterStateSnapshot>>;
private userEmailAddress: string;
constructor(private eventService: AppEventsService,
@Optional() @Inject(TRACK_ROUTE_CHANGES) private trackRouteChanges: boolean) {
this.pageChangeEvents = eventService.eventStream.pipe(
filter((event: AppEventInterface<RouterStateSnapshot>) => this.trackRouteChanges && event.name === GlobalAppEvents.RouteChangeComplete)
);
this.initializeSubscriptions();
}
private initializeSubscriptions(): void {
this.pageChangeEvents.subscribe(this.onPageChange.bind(this));
}
private onPageChange(routeChangeEvent: AppEventInterface<RouterStateSnapshot>): void {
const pageName = this.inferPageName(routeChangeEvent.data);
// do stuff with the page name
}
private inferPageName(routerSnapshot: RouterStateSnapshot): string {
let pageName = 'Undefined';
let routeNode = routerSnapshot.root;
while (routeNode) {
if (routeNode.data.pageName) {
pageName = routeNode.data.pageName;
break;
} else {
routeNode = routeNode.parent;
}
}
return pageName;
}
}
上面的代码为每个页面名称生成'Undefined'
,因为运行时路由数据的值是一个空对象。
如何构建此体系结构,使每个组件都不需要了解 AppEventsService 和 AnalyticsService ?