javascript - 如何在 Angular 12 中读取本地 JSON 文件?
问题描述
我正在尝试从本地 JSON 文件中读取数据,该文件存储了我的应用程序的一些配置数据。ng build
在 Angular CLI 中使用命令时,我不断收到错误消息。
我的组件的 TypeScript 文件:my-component.ts
...
import credentials from './config/credentials.json';
export class MyComponent implements OnInit {
...
// Properties
username: string = credentials.username;
...
}
JSON 配置文件,存储在“/config”位置:credentials.json
{
"credentials" : {
"username" : "my_user_name",
...
}
}
我收到错误消息:Error: Should not import the named export 'credentials' (imported as 'credentials') from default-exporting module (only default export is available soon)
是什么导致了这个错误?它似乎与此处描述的问题相似。
解决方案
对于 Angular 版本 12,您还需要做两件事。
首先,您需要在文件中添加一些行。在这里参考这个问题。注意:这些不同于 Angular 版本 11。
{
...
"compilerOptions": {
...
"resolveJsonModule": true, // add this line...
"esModuleInterop": true, // this line...
...
},
...
"allowSyntheticDefaultImports": true // and this line, notice this one is outside of "compiler options"
}
其次,您需要添加一个let
语句。以上对我来说并不适用,但通过这一步,我让它工作了。参考这篇博文。
我的组件的 TypeScript 文件:my-component.ts
...
import credentials from './config/credentials.json';
let my_username = credentials.username; // ADD THIS LINE
export class MyComponent implements OnInit {
...
// Properties
username: string = my_username; // NOW USE THE NEW VARIABLE
...
}
诚然,我不完全理解为什么会这样,但它确实有效。该来源似乎表明它与变量范围有关。
推荐阅读
- reactjs - 服务器端渲染功能如何利用 DB 调用?
- javascript - 如何使用事件监听器退出 selenium-webdriver?
- ios - Swift Firebase 在删除时触发 Cloud Function
- android - 自定义可扩展列表的可能性
- python - AttributeError:“int”对象没有属性“map”
- amazon-web-services - Lambda@Edge 是否会在失败时重试?
- bash - Yad list 获取函数中所选行的值
- python - 我的一个精灵不会出现在我的 pygame 代码中
- python - 按百分比标准化滚动窗口(熊猫)
- c# - OleDb.OleDbException 条件表达式中的数据类型不匹配