我有一个 Angular 应用程序,在一个组件上,我想检测 Angular 应用程序域之外的路由。
例如:用户正在处理重要信息的上传组件上,用户通过路由器、window.location.href、window.location.assign、手动输入网址、点击广告上的网址导航出应用程序。我想以角度检测该事件,并根据条件,执行路线或阻止它。
我知道有一种通过路由器检测路由变化的方法,但它不适用于 window.location 路由或单击广告弹出窗口中的链接时。以下是我尝试过的路由器方法,但没有成功:
this.router.events.forEach((e: any) => {
if (e instanceof NavigationStart) {
console.log('routing to ' + JSON.stringify(e));
}
});
基本上,我想阻止应用程序的一个组件上的所有外部路由,同时维护到应用程序路由的路由。这可能吗?
您可以将事件即 beforeunload 与 HostListener 一起使用,如下所述。
import { Component, HostListener } from '@angular/core';
import { Router, NavigationStart } from '@angular/router';
@Component({
selector: 'app-upload',
templateUrl: './upload.component.html',
styleUrls: ['./upload.component.css']
})
export class UploadComponent {
constructor(private router: Router) {
// Subscribe to Angular Router events
}
@HostListener('window:beforeunload', ['$event'])
unloadNotification($event: any): void {
// You can add custom logic here to prompt the user before leaving the page
// For example, return a confirmation message
$event.returnValue = true;
}
}
希望对您有帮助。