繁体   English   中英

如何读取 Angular 12 中的本地 JSON 文件?

[英]How do I read a local JSON file in Angular 12?

我正在尝试从本地 JSON 文件中读取数据,该文件存储了我的应用程序的一些配置数据。 在 Angular CLI 中使用ng build命令时,我不断收到错误消息。

我的组件的 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
    ...
}

诚然,我不完全理解为什么会这样,但它确实有效。 该来源似乎表明它与变量范围有关。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM