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

在users.component.ts中使用setTimeout报错:Cannot find module 'timers'

解决Angular中setTimeout报错"Cannot find module 'timers'"的问题

嘿,我来帮你搞定这个问题!你遇到的报错根源很简单:timers是Node.js的核心模块,只在Node环境中可用,但你的Angular项目是运行在浏览器里的,浏览器根本没有这个模块,所以导入它肯定会报错,而且完全没必要这么做。

正确的做法:

  1. 首先删掉那行错误的导入代码:
    // 删掉这行!
    import { setTimeout } from 'timers'
    
  2. 直接使用浏览器全局的setTimeoutAPI就行,它不需要任何额外导入。比如在你的users.component.ts里这么写:
    import { Component, OnInit } from '@angular/core';
    
    @Component({
      selector: 'app-users',
      templateUrl: './users.component.html',
      styleUrls: ['./users.component.css']
    })
    export class UsersComponent implements OnInit {
      ngOnInit(): void {
        // 直接调用全局的setTimeout
        setTimeout(() => {
          // 这里写你要延迟执行的逻辑
          console.log('2秒后执行的代码');
        }, 2000); // 延迟时间,单位毫秒
      }
    }
    

额外提示(如果遇到TypeScript类型报错):

如果TypeScript提示找不到setTimeout的类型定义,那是因为你的tsconfig.json里没包含浏览器环境的类型库。打开tsconfig.json,确保compilerOptions里的lib数组包含dom:

{
  "compilerOptions": {
    "lib": ["es2020", "dom"],
    // 其他配置项...
  }
}

这样TypeScript就能识别浏览器的全局API类型了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:21:10