[英]How to trigger a Javascript event on url change
當前,我正在處理一個角度項目,我需要觸發一個路由更改/ URL從一個頁面到另一頁面的更改事件(因為這是一個角度項目頁面,將不會刷新)。
我曾嘗試在index.html頁面中使用不同的場景,如下所示:
window.onbeforeunload = function () {
//not fit;
});
window.onhashchange = function () {
//not fit;
});
我們是否可以使用其他解決方案來觸發有關url更改的事件(我不想在angular中使用偵聽器)。
您可以通過甚至在窗口上實現hashchange來做到這一點
而且,如果您使用的是jQuery,則此插件可能會為您提供幫助。
或者在您的情況下檢查純JS代碼
function hashHandler() {
this.oldHash = window.location.hash;
this.Check;
var that = this;
var detect = function() {
if(that.oldHash != window.location.hash) {
alert("HASH CHANGED - new has" + window.location.hash);
that.oldHash = window.location.hash;
}
};
this.Check = setInterval(function() { detect() }, 100);
}
var hashDetection = new hashHandler();
帶有路由器的angular的純演示代碼示例:
import { Component, OnInit } from '@angular/core'; // I import Location so that I can query the current path
import { Location } from '@angular/common'; // I also import Router so that I can subscribe to events
import { Router } from '@angular/router';
@Component(
{ selector: 'app-top-nav',
templateUrl: './top-nav.component.html',
styleUrls: ['./top-nav.component.scss'] }
)
export class TopNavComponent implements OnInit {
route: string;
constructor(location: Location, router: Router) { // within our constructor we can define our subscription
// and then decide what to do when this event is triggered.
// in this case I simply update my route string.
router.events.subscribe((val) => { if(location.path() != '') { this.route = location.path(); } else { this.route = 'Home' } });
}
ngOnInit() {
}
}
上面的代碼應該工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.