使用装饰方法的组件的基类并未在继承的组件中拾取
我在组件中使用此代码在用户刷新页面之前进行确认,以避免错误地丢失更改:
@HostListener('window:beforeunload', ['$event'])
unloadNotification($event: any) {
if (!this.canDeactivate()) {
$event.returnValue = '';
$event.preventDefault();
}
}
为了避免在其他组件中重复该代码,我想创建一个基类,
@Injectable()
export abstract class ComponentCanDeactivate {
abstract canDeactivate(): boolean;
@HostListener('window:beforeunload', ['$event'])
unloadNotification($event: any) {
if (!this.canDeactivate()) {
$event.returnValue = '';
$event.preventDefault();
}
}
但现在扩展此基类的组件类,似乎没有监听 beforeunload 事件。 Angular 是否没有选择装饰器,因为它位于基类上?我在以下内容中看到这项工作: 示例 使用 Angular 11,我正在使用 Angular 13。不知道这是否改变了行为,或者我是否遗漏了一些东西
I'm using this code in my component to have a confirmation before the user refreshes the page, to avoid losing changes by mistake:
@HostListener('window:beforeunload', ['$event'])
unloadNotification($event: any) {
if (!this.canDeactivate()) {
$event.returnValue = '';
$event.preventDefault();
}
}
To avoid duplicating that code in other components I wanted to create a base class like
@Injectable()
export abstract class ComponentCanDeactivate {
abstract canDeactivate(): boolean;
@HostListener('window:beforeunload', ['$event'])
unloadNotification($event: any) {
if (!this.canDeactivate()) {
$event.returnValue = '';
$event.preventDefault();
}
}
but now the components extending this base class, don't seem to be listening to the beforeunload event. Is the decorator not being picked by Angular because it is on the base class? I see this work in this: example using angular 11, and I'm using angular 13. don't know if that changed the behavior or if I'm missing something
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要抽象类是
component
而不是注射
https://stackblitz.com/edit/Edit/Angular-ivy-ivy-ivy-ivy-xsmfdn?file=src/app/app/app/concrete/concrete/concrete/concrete.concrete.component.component.ts
Angular支持继承
HOSTLISTENER
,但是当您混合这样的装饰器时,似乎会感到困惑。You need the abstract class to be a
Component
rather than anInjectable
https://stackblitz.com/edit/angular-ivy-xsmfdn?file=src/app/concrete/concrete.component.ts
Angular supports inheriting
HostListener
but seems to get confused when you mix decorators like that.