从文件中读取JSON文件在Angular中
从文件中读取JSON文件在Angular中
我有一个JSON文件config.json
保存在src/app/config
目录中。
[ "caseSensitive", "matchKeywords", "items" ]
我需要读取该文件并获取JSON文件的内容,而不进行解析。
在搜索后,我找到了两种方法:
- 在
tsconfig.json
文件中添加"resolveJsonModule": true
- 声明一个类型模块
declare module "*.json" {}
并导入JSON文件:
import * as data from './app/config/config.json'; export class SchemaService { constructor() { } getConfig() { console.log('bool: ', data); // 输出截图中的结果 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中从文件中读取JSON文件的问题是因为默认情况下,Angular无法直接将JSON文件作为模块进行导入和使用。解决这个问题的方法是在tsconfig.json文件中添加两行代码:"resolveJsonModule": true和"allowSyntheticDefaultImports": true。添加这两行代码后,就可以在应用程序的任何位置导入JSON文件了。
具体解决方法如下:
1. 打开tsconfig.json文件。
2. 在该文件中添加以下两行代码:
"resolveJsonModule": true,
"allowSyntheticDefaultImports": true
3. 保存并关闭tsconfig.json文件。
4. 在需要使用JSON文件的组件中,通过以下代码导入JSON文件:
import * as Characters from './configs/characters.json';
5. 在组件中访问JSON文件的对象,可以使用以下代码:
export class CharactersComponent { public characters: CharacterModel[] = (Characters as any).default; }
通过以上步骤,就可以在Angular应用程序中成功读取JSON文件并使用其中的对象了。
从上述内容中可以得出以下问题的原因和解决方法:
问题:在Angular中从文件中读取JSON文件。
原因:Angular中的import语句不能直接导入.json文件,因此需要寻找替代方法。
解决方法:
1. 创建一个名为config.json.ts的文件,注意文件扩展名为.ts而不是.json。
2. 在config.json.ts文件中定义JSON对象,将其赋值给CONFIG变量,例如:
export const CONFIG = { "say": "hello world" }
3. 在其他需要使用该JSON对象的.ts文件中,使用import语句导入config.json.ts文件,例如:
import { CONFIG } from './config.json'; // ... console.log(CONFIG.say); // ...
优点:
1. 仍然可以在config.json.ts文件上使用tslint/eslint进行代码检查。
2. 大多数编辑器将为您提供自动补全功能。