2015-11-13 77 views
7

我正在使用Aurelia框架。 每次用戶導航到新路線/頁面時,我都要在應用文件(app.ts/app.js)中獲取信息navigationInstruction確定Aurelia中的當前路線

我試圖在應用程序的生命週期事件(激活和綁定)中獲取此信息,但沒有可用的信息。

任何人都可以幫助我解決這個問題。

在此先感謝。

回答

9

訂閱路由器的導航「成功」事件:

import {EventAggregator} from 'aurelia-event-aggregator'; 
import {inject} from 'aurelia-dependency-injection'; 

@inject(EventAggregator) 
export class App { 
    constructor(eventAggregator) { 
    this.eventAggregator = eventAggregator; 
    } 

    navigationSuccess(event) { 
    let instruction = event.instruction;  
    // todo: do something with instruction... 
    } 

    attached() { 
    this.subscription = this.eventAggregator.subscribe(
     'router:navigation:success', 
     this.navigationSuccess.bind(this)); 
    } 

    detached() { 
    this.subscription.dispose(); 
    } 
} 

下面是使用ES7功能結合和ES6解構一個稍微不同的版本:

import {EventAggregator} from 'aurelia-event-aggregator'; 
import {inject} from 'aurelia-dependency-injection'; 

@inject(EventAggregator) 
export class App { 
    constructor(eventAggregator) { 
    this.eventAggregator = eventAggregator; 
    } 

    navigationSuccess({ instruction }) { 
    // todo: do something with instruction... 
    } 

    attached() { 
    this.subscription = this.eventAggregator.subscribe(
     'router:navigation:success', 
     ::this.navigationSuccess); 
    } 

    detached() { 
    this.subscription.dispose(); 
    } 
} 
+0

好東西對於我們這些手動構建導航 - 謝謝 – mujimu