Angular:无法获取路由器事件

时间:2017-09-04 05:19:12

标签: angular angular2-routing

我试图从组件中获取上一个路由。但是当我路由到该组件时,我的路由器事件订阅代码不起作用。当我离开组件时,它可以工作。即使我离开,我也无法获取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();
  }

0 个答案:

没有答案