1
使用Angular 2,我有一個組件訂閱了基於URL哈希的服務。 URL更改不會調用子組件。我認爲這將需要路線,但位置可能更合適。我如何傾聽並對流行狀態事件做出反應?Angular 2 - 組件如何識別URL更改?
使用Angular 2,我有一個組件訂閱了基於URL哈希的服務。 URL更改不會調用子組件。我認爲這將需要路線,但位置可能更合適。我如何傾聽並對流行狀態事件做出反應?Angular 2 - 組件如何識別URL更改?
如果你想聽路由改變,你可以使用路由器。
import {Location} from '@angular/common';
import {Router} from '@angular/router'
export class SomeComponent {
constructor(router:Router, private location:Location) {
router.changes.subscribe(() => this.routeChanged());
}
private routeChanged():void {
var path:string = this.location.path();
console.log("Path:" + path);
}
}
這是你想要做的嗎?
你在哪裏找到Router.changes()?它未在[路由器文檔](https://angular.io/docs/js/latest/api/router/Router-class.html)中列出 – ebakunin
https://github.com/angular/angular/blob/b30ddfbfc5192f526ceaac525cf6965635831c46 /modules/%40angular/router/src/router.ts#L74。 https://angular.io/docs/ts/latest/api/router/index/Router-interface.html還顯示「'變化:Observable' 可觀察的或URL從路由器更改。」 –
@GünterZöchbauer當我運行上面的代碼時出現錯誤。代碼製作是否正確?我正在運行2.0.0-beta.9版本。 'TypeError:router.changes is undefined' – ebakunin