在Angular中,通过HostListener监听window的“beforeunload”事件,可以检查页面是否将被卸载或关闭。但是,如果您使用了RxJS的takeUntil操作符来取消该绑定,则可能会导致代码卡在那里。下面是一个简单的解决方法,您可以在destroy中手动释放subscription来解决这个问题。
import { Component, HostListener, OnDestroy } from '@angular/core';
import { Subject, Subscription } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
@Component({
selector: 'app-root',
template: `
Example component
`
})
export class AppComponent implements OnDestroy {
private onDestroy$ = new Subject();
private subscription: Subscription;
constructor() {
this.subscription = this.checkClosed().pipe(
takeUntil(this.onDestroy$)
).subscribe();
}
@HostListener('window:beforeunload')
checkClose(): void {
console.log('Window is about to unload');
}
private checkClosed() {
return new Observable(observer => {
setTimeout(() => {
observer.next();
observer.complete();
}, 1000);
});
}
ngOnDestroy() {
this.onDestroy$.next();
this.onDestroy$.complete();
this.subscription.unsubscribe();
}
}
在这个例子中,我们手动释放了subscription,并且在组件销毁时使用takeUntil释放subscription和Subject。这就可以避免卡住的问题。