【发布时间】:2016-06-25 02:06:01
【问题描述】:
如何在 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() in service 不工作了。
我做错了什么?
【问题讨论】:
标签: javascript angular typescript angular2-routing