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

Angular读取本地JSON到InputData数组报错:subscribe属性不存在

解决本地JSON文件读取与类型数组赋值问题

错误原因

你直接导入的本地JSON文件是同步加载的静态数组数据,并非RxJS的Observable对象,所以不存在subscribe方法,这就是报错TS2339: Property 'subscribe' does not exist on type '{}'的核心原因。

修正步骤与代码

  1. 确保TypeScript支持JSON导入(若未配置)
    在项目根目录的tsconfig.json中添加以下配置:

    {
      "compilerOptions": {
        // 保留原有其他配置
        "resolveJsonModule": true,
        "esModuleInterop": true
      }
    }
    
  2. 修正组件代码
    直接将导入的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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 10:55:21