【发布时间】:2021-08-27 18:23:35
【问题描述】:
我有一个 JSON 文件 config.json 保存在 src/app/config 目录中。
[
"caseSensitive",
"matchKeywords",
"items"
]
我必须读取文件并在不解析的情况下获取 JSON 文件的内容。
搜索了一下,有两种方法
- 将
"resolveJsonModule": true添加到tsconfig.json文件中 - 声明一个打字模块
declare module "*.json" {}
并将 JSON 导入为
import * as data from './app/config/config.json';
export class SchemaService {
constructor() { }
getConfig() {
console.log('bool: ', data); // Output in screenshot
console.log('type: ', typeof BooleanData); // object
console.log('parsed: ', JSON.stringify(BooleanData));
}
}
但两种方式都将解析后的输出设为
JSON.stringify(BooleanData) 语句没有给出实际的 JSON 文件,而是将数组项更改为键值,其中索引表示为键
{
"0":"caseSensitive",
"1":"matchKeywords",
"2":"items"
}
如何在 Angular 中读取原始 JSON(无需解析),或者至少将对象转换为 JSON?
【问题讨论】:
-
这能回答你的问题吗? Angular 5 Service to read local .json file
-
@R.Richards 这实际上并没有回答我的问题。使用
HttpClient将在没有连接时停止工作,并且它需要将数据文件放在assets目录中,而在我的情况下,它在其模块目录中。 -
看起来 jsonModule 应该始终是一个对象。您可以尝试 { data: [ "caseSensitive", "matchKeywords", "items" ]} 然后导入为 import { data } from './app/config/config.json';
标签: json angular typescript