Angular:从JavaScript类在服务中创建对象时出现错误
问题原因
你的readData.js中定义的Configs类默认处于全局作用域,而TypeScript服务文件里的declare var Configs: any又重复声明了这个全局标识符,导致浏览器加载时触发重复声明的语法错误。
解决方法
方法一:改用模块化导入(推荐)
将JS文件改为模块化导出,符合Angular的模块化规范:
- 修改
src/assets/readData.js,添加导出语句:
export class Configs { constructor() { this.Config = ""; this.branches = this.readBranches(); this.setBranch(); // .... } // .... }
- 在
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
相关产品推荐
相关产品推荐

