Angular读取本地JSON到InputData数组报错:subscribe属性不存在
解决本地JSON文件读取与类型数组赋值问题
错误原因
你直接导入的本地JSON文件是同步加载的静态数组数据,并非RxJS的Observable对象,所以不存在subscribe方法,这就是报错TS2339: Property 'subscribe' does not exist on type '{}'的核心原因。
修正步骤与代码
确保TypeScript支持JSON导入(若未配置)
在项目根目录的tsconfig.json中添加以下配置:{ "compilerOptions": { // 保留原有其他配置 "resolveJsonModule": true, "esModuleInterop": true } }修正组件代码
直接将导入的JSON数组赋值给目标数组,通过类型断言让TypeScript识别其类型:import dataset from "./dataset.json"; // 注意JSON文件路径要正确 export interface InputData { _id: { $oid: string; // 优先使用TypeScript小写基本类型,而非大写包装对象 }; id: string; expNumber: number; passed: boolean; } @Component({ selector: "app-read-data", templateUrl: "./read-data.component.html", styleUrls: ["./read-data.component.scss"], }) export class ReadDataComponent implements OnInit { public data: InputData[] = []; // 初始化空数组,避免undefined constructor() {} ngOnInit(): void { // 直接赋值并做类型断言 this.data = dataset as InputData[]; console.log("DATA", this.data); } }
额外说明
- 类型定义中优先使用
string/number/boolean这些小写基本类型,大写的String/Number/Boolean是JavaScript的包装对象,极少用于TypeScript类型声明。 - 确认JSON文件的导入路径正确,若文件不在组件同级目录,需调整路径(比如
../assets/dataset.json)。
内容的提问来源于stack exchange,提问作者JukeboxHero
相关产品推荐
相关产品推荐

