2016-03-10 9 views
41

角度2ルータの状態変化を監視するにはどうすればよいですか?角2ルータイベントリスナー

私は、このイベントを使用角度1.xでは:

だから、
$rootScope.$on('$stateChangeStart', 
    function(event,toState,toParams,fromState,fromParams, options){ ... }) 

、私は角2に、このイベントリスナーを使用する場合:

window.addEventListener("hashchange",() => {return console.log('ok')}, false); 

それは 'OK' を返していない、その変更JSからの状態、ブラウザのhistory.back()関数が実行されます。サービスとして

使用router.subscribe()関数:ルーティングでのinit成分で

import {Injectable} from 'angular2/core'; 
import {Router} from 'angular2/router'; 

@Injectable() 
export class SubscribeService { 
    constructor (private _router: Router) { 
     this._router.subscribe(val => { 
      console.info(val, '<-- subscribe func'); 
     }) 
    } 
} 

噴射サービス:

import {Component} from 'angular2/core'; 
import {Router} from 'angular2/router'; 

@Component({ 
    selector: 'main', 
    templateUrl: '../templates/main.html', 
    providers: [SubscribeService] 
}) 
export class MainComponent { 
    constructor (private subscribeService: SubscribeService) {} 
} 

私は、この例のような他の成分は、このサービスを注入。それから、状態が変わり、console.info()が動作しない状態になります。

私は間違っていますか?

+0

[ gular 2?](https://stackoverflow.com/questions/33520043/how-to-detect-a-route-change-in-angular-2) –

答えて

96

import {Router} from 'angular2/router'; 

class MyComponent { 
    constructor(router:Router) { 
    router.subscribe(...) 
    } 
} 

注ルータを注入し、ルートの変更イベントをサブスクライブ

constructor(router:Router) { 
    router.events.subscribe(event:Event => { 
    if(event instanceof NavigationStart) { 
    } 
    // NavigationEnd 
    // NavigationCancel 
    // NavigationError 
    // RoutesRecognized 
    }); 
} 

古い新しいルータ

新しいルータの場合は、あなたがそれをインポートしない場合instanceofは動作しませんとエラーが上昇しますのでrouterモジュール

import { Router, NavigationStart } from '@angular/router'; 

からNavigationStartをインポートすることを忘れないでください。

は、すべての状態の変化に耳を傾け、デフォルトRouterOutletを拡張し、 'アクティブ' に独自のロジックを追加し、ハンドラを '無効化' することも

+0

'router.subscribe(...)'を実行する必要がありますか?すべてのクラスで、または私はそれらを一度に実行できますか?ドキュメントでは、サブスクリプション機能で入力する必要があるパラメータを理解できません。あなたは完全な例を書くことができますか? –

+0

グローバルサービスで一度実行してから、アクセスを取得する場所にサービスを注入できます。 –

+0

サービスとして他のコンポーネントに注入すると、データは返されません –

-1

参照してください。ここでの 'カスタムルーターアウトレット' の例からコピー

import {Directive} from 'angular2/core'; 
import {Router, RouterOutlet, ComponentInstruction} from 'angular2/router'; 

@Directive({ 
    selector: 'router-outlet' 
}) 

export class MyOwnRouterOutlet extends RouterOutlet { 
    ... 

    activate() { 
    console.log('Hello from the new router outlet!'); 
    } 
} 

https://auth0.com/blog/2016/01/25/angular-2-series-part-4-component-router-in-depth/

5

あなたはGünterZöchbauer @としてinstanceofを使用することができますが

this.router.events.subscribe(event => { if(event instanceof NavigationStart) { // do something... } } 

に答えたり、あなたはlazierアプローチを使用することができますしかし、関数がまだ動作している間はコンストラクタ名を簡単に変更できることを忘れないでください!

this.router.events.subscribe(event => { 
    if(event.constructor.name === "NavigationStart") { 
    // do something... 
    } 
}); 
+10

'instanceof'を使いたくない場合の考慮事項は何ですか? –

+2

このアプローチは、コンストラクタ名が変更される可能性があるため、minificationにも脆弱です。例えば、 'event.constructor.name'は' 'A '' –

0

角度2つのルータのイベントは異なるクラスがあり、何がどちらかNavigationEndNavigationCancelNavigationError、またはNavigationStartすることができ、観察router.eventsからサブスクリプションに渡されます。ルーティング更新を実際にトリガーするものはNavigationEndです。 縮小クラス名がマングルされます後にそれが正常に動作しませんので、

私は離れinstanceofまたはevent.constructor.nameを使用してからご利用いただけます。

あなたが "app.modules.ts" ファイルに行き、ここangular2でhttps://angular.io/docs/ts/latest/api/router/index/Router-class.html

this.routerEventSubscription = this._router.events.subscribe((event: any) => { 
    if (this._router.isActive(events.url, false)) { 
    // true if the url route is active 
    } 
} 
0

を示し、代わりにルータのisActive機能を使用することができます - 真のショーをenableTracingに>輸入

RouterModule.forRoot(
     appRoutes, 
     { 
     enableTracing: true 
     } 
) 

をコンソールのrouteEvents enablelightingの falseコンソールのrouteEventsを非表示にする