【问题标题】:How do I read a local JSON file in Angular 12?如何在 Angular 12 中读取本地 JSON 文件?
【发布时间】:2021-08-21 22:34:50
【问题描述】:

我正在尝试从本地 JSON 文件中读取数据,该文件存储了我的应用程序的一些配置数据。使用 ng build command in the 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)

是什么导致了这个错误?好像和issue described here很像。

【问题讨论】:

    标签: javascript json angular typescript


    【解决方案1】:

    对于 Angular 12 版,您还需要做两件事。

    首先,您需要在文件中添加一些行。 Reference this question here。注意:这些不同于 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 语句。以上对我来说并不适用,但通过这一步,我让它发挥作用。 Reference this blog post.

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

    诚然,我不完全理解 为什么 这有效,但它有效。 This source 似乎暗示它与变量范围有关。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-25
      • 1970-01-01
      • 1970-01-01
      • 2018-04-22
      • 2018-02-11
      • 2020-03-21
      • 1970-01-01
      • 2017-07-07
      相关资源
      最近更新 更多