如何在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路由器事件監聽器
元芳怎么了
2019-11-29 11:06:37