大佬教程收集整理的这篇文章主要介绍了Angular 2路由器事件监听器,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
constructor(router:router) {
router.events.subscribe(event:Event => {
if(event instanceof NavigationStart) {
}
// NavigationEnd
// NavigationCancel
// NavigationError
// RoutesRecognized
});
}
注入路由器并订阅路由更改事件
@R_301_5565@ {Router} from 'angular2/router';
class MyComponent {
constructor(router:router) {
router.subscribe(...)
}
}
对于新路由器,请不要忘记NavigationStart
从router
模块导入
@R_301_5565@ { Router, NavigationStart } from '@angular/router';
因为如果不导入,instanceof
它将无法正常工作,并且会出现错误NavigationStart is not defined
。
如何在Angular 2路由器中监听状态变化?
在Angular 1.x中,我使用了以下事件:
$rootScope.$on('$stateChangeStart',function(event,toState,toParams,fromState,fromParams,options){ ... })
因此,如果我在Angular 2中使用此事件监听器:
window.addEventListener("hashchange",() => {return console.log('ok')},falsE);
它不会返回“ ok”,然后从JS更改状态,只有在浏览器history.BACk()函数运行之后才可以。
使用router.subscribe()函数作为服务:
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()无法正常工作。
我做错了什么?
以上是大佬教程为你收集整理的Angular 2路由器事件监听器全部内容,希望文章能够帮你解决Angular 2路由器事件监听器所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。