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

Angular:从JavaScript类在服务中创建对象时出现错误

问题原因

你的readData.js中定义的Configs类默认处于全局作用域,而TypeScript服务文件里的declare var Configs: any又重复声明了这个全局标识符,导致浏览器加载时触发重复声明的语法错误。

解决方法

方法一:改用模块化导入(推荐)

将JS文件改为模块化导出,符合Angular的模块化规范:

  1. 修改src/assets/readData.js,添加导出语句:
export class Configs {
  constructor() {
    this.Config = "";
    this.branches = this.readBranches();
    this.setBranch();
    // ....
  }

  // ....
}
  1. 在data.service.ts中直接导入,无需declare:
import { Injectable } from '@angular/core';
import { Configs } from '../assets/readData.js';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  configs: any;

  constructor() { 
    this.configs = new Configs();
  }
}

如果Angular无法识别assets目录下的JS模块,可以将readData.js移至src/app目录,或调整tsconfig.json中的include配置,确保模块能被正确解析。

方法二:保留全局但避免重复声明

去掉TS中的declare语句,通过window对象访问全局类:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  configs: any;

  constructor() { 
    this.configs = new (window as any).Configs();
  }
}

方法三:手动挂载全局类到window

修改readData.js,将类挂载到window对象,避免直接暴露全局标识符:

class Configs {
  constructor() {
    this.Config = "";
    this.branches = this.readBranches();
    this.setBranch();
    // ....
  }

  // ....
}

window.Configs = Configs;

之后在TS中同样通过(window as any).Configs实例化即可。

关键注意事项

无论采用哪种方法,都要确保readData.js在Angular应用加载前被引入,可在index.html中添加脚本标签:

<script src="assets/readData.js"></script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 17:57:18