json - 从 Angular 中的文件中读取 JSON 文件
问题描述
我config.json
在目录中保存了一个 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?
解决方案
您可以使用@amer-yousuf 提供的快速修复,但它也可以让您将任何.js
文件导入您的代码库。我不会喜欢那个。这是另一种方法
定义您的config.json.ts
(注意它以.ts
而不是结尾.json
)如下所示
export const CONFIG = { // your JSON is assigned to CONFIG variable
"say": "hello world"
}
.ts
在您要使用的其他文件中,使用类似以下代码的内容
import { CONFIG } from './config.json';
// ...
console.log(CONFIG.say);
// ...
这种方法的好处:
- 你仍然可以在 config.json.ts 上使用 tslint/eslint
- 大多数编辑器会为您自动完成
推荐阅读
- php - 查询从数据库中删除记录,但表行不淡出那一个
- c# - MediaCapture.PrepareLowLagRecordToStorageFileAsync() 在 HoloLens 上引发“类未注册”异常
- vb.net - 在 ms 访问中以编程方式创建列到表
- reactjs - react-cookie-consent 在点击时存储数据两次
- c# - “索引超出数组边界”错误背后的原因
- mysql - MySQL undo log 不断增长
- java - 共享首选项重新调整为 null
- javafx - 在javafx中画一条带过渡的线
- c++ - 子程序,不使用 pow,带参数和返回
- java - 当我使用 requestDispatcher.forward 函数时,为什么我的代码没有打印正确的结果?