2017-01-09 33 views
2

我有用於Angular 1的ui-router的經驗,現在我想知道如何在ui-router-ng2中收聽$stateChangeStart

請讓我知道如何下角1個的代碼都可以在角2

$rootScope.$on('$stateChangeStart', function(event, next) {}); 
+0

您是否嘗試過文檔? – Rabban

回答

2

尼斯Plunkr來完成,例如:

https://plnkr.co/edit/k8PgPKRNu0llT521p5R5?p=preview

在UI上路由器,NG2你有所有狀態生命週期的服務(TransitionService):

1)你需要在你的構造函數中注入服務:

import {TransitionService} from "ui-router-ng2"; 
constructor(private transitionService:TransitionService) {} 

2)回調函數:

transitionService.onStart({},()=>{ 
    console.log("state changed"); 
}) 

上,您可以把條件例如第一個值:

transitionService.onStart({from: 'home', to: 'other'},()=>{ 
    console.log("state changed"); 
}) 

(回調只會打電話的時候,目前的狀態是「家'和下一個狀態'其他')

**您還可以調用onSuccess,onError,onEnter,onFinish和更多...

我希望你覺得它有幫助,

祝你好運!

+0

所有關於轉換服務:https://ui-router.github.io/ng2/docs/latest/classes/transition.transitionservice.html –

+1

關於在組件中添加轉換掛鉤的警告:它們不會自動清理,因此如果使用'ngOnDestroy'銷燬組件將被明確清除。 –

+1

我的建議是不在組件中添加Transition Hooks。 最好在服務中添加Transition Hooks,其中構造函數只調用一次。 – YairTawil

相關問題