我试图从组件中获取上一个路由。但是当我路由到该组件时,我的路由器事件订阅代码不起作用。当我离开组件时,它可以工作。即使我离开,我也无法获取NavigationEnd
类型的事件。请看一下我的代码。
在路由器配置中:
{
path: 'transactions',
component: TransactionsComponent,
canActivate: [CanActivateAuthGuardService],
children: [
{
path: '',
component: ViewTransactionsComponent,
children: [
{
path: '',
redirectTo: 'my-transactions',
pathMatch: 'full'
},
{
path: 'my-transactions',
component: MyTransactionsComponent
},
{
path: 'transactions-pending-my-approval',
component: PendingTransactionsComponent
}
]
},
{
path: 'transaction-details',
component: TransactionDetailsComponent
},
{
path: 'create-transaction',
component: CreateTransactionComponent,
data: { title: 'Create Transaction' }
},
{
path: 'edit-transaction/:name',
component: CreateTransactionComponent,
data: { title: 'Edit Transaction' }
}
]
}
在CreateTransactionComponent
:
ngOnInit() {
this.transactionService.getDynamicTableData().then(categories => {
this.categories = categories;
});
this.dataSubscription = this.route.data.subscribe(data => this.title = data.title);
this.routeParamsSubscription = this.route.params.subscribe(params => this.name = params.name);
this.eventSubscription = this.router.events
.subscribe(event => {
console.log(event); //not working when I enter this component but works when I leave
});
}
ngOnDestroy() {
this.dataSubscription.unsubscribe();
this.routeParamsSubscription.unsubscribe();
this.eventSubscription.unsubscribe();
}