You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular:如何在构造函数中获取@HostListener的属性?

问题分析与解决方案

核心问题

  1. 构造函数执行时机过早:组件构造函数在@HostListener绑定的事件触发前就已经执行了,此时dateTimeNow还未被赋值,自然拿不到事件里的日期值。
  2. 超时逻辑设计有误:你当前是固定从10开始倒计时,但正确的无操作超时逻辑应该是用户每次有鼠标移动时重置倒计时,而非不管用户操作一直递减。

修改方案

  1. 在鼠标移动事件中同时更新dateTimeNow和重置计数器
  2. 优化定时器管理,避免内存泄漏
  3. 移除构造函数中对未触发事件值的不合理依赖

修改后的完整代码

import { Component, HostListener, OnInit, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-nav-menu',
  templateUrl: './nav-menu.component.html',
  styleUrls: ['./nav-menu.component.css']
})
export class NavMenuComponent implements OnInit, OnDestroy {
  isExpanded = false;
  active: boolean = false;
  counter: number = 10;
  dateTimeNow: Date | undefined;
  private intervalId: any;

  constructor(private router: Router) {}

  ngOnInit() {
    // 组件初始化完成后启动定时器
    this.startTimer();
  }

  ngOnDestroy() {
    // 组件销毁时清理定时器,防止内存泄漏
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }
  }

  @HostListener('document:mousemove', ['$event'])
  onMouseMove(e: MouseEvent) {
    // 每次鼠标移动时更新最后操作时间,同时重置倒计时
    this.dateTimeNow = new Date();
    this.counter = 10;
    console.log('最后鼠标移动时间:', this.dateTimeNow);
  }

  private startTimer() {
    this.intervalId = setInterval(() => {
      this.counter--;
      console.log('剩余时间:', this.counter);

      if (this.counter === 0) {
        clearInterval(this.intervalId);
        this.router.navigateByUrl('/');
      }
    }, 1000);
  }
}

关键说明

  • 把定时器启动逻辑移到ngOnInit钩子,此时组件已完成初始化,@HostListener事件绑定也已生效
  • 每次鼠标移动时直接更新dateTimeNow并重置counter,保证倒计时始终基于用户最后一次操作开始计算
  • 实现OnDestroy钩子清理定时器,避免组件销毁后定时器仍在运行导致内存泄漏
  • 现在你可以在组件任意位置访问this.dateTimeNow,它始终存储着用户最后一次鼠标移动的时间

内容的提问来源于stack exchange,提问作者john

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 01:25:15