【问题标题】:Import a local json file with Angular使用 Angular 导入本地 json 文件
【发布时间】:2020-01-09 02:51:39
【问题描述】:

我的项目之外有一个简单的.json 文件。像这样:

| common
    | configuration.json
| angular-app
    | src
        | app
            | my-component
                | my-component.component.ts
    | angular.json

my-component.component.ts,我想导入configuration.json。我试过 import configuration from '../../../../common.configuration.json' 但 Angular 只是不断抛出这个错误:

ERROR in src/app/record/record.component.ts(4,23): error TS2732: Cannot find module '../../../../common/configuration.json'. Consider using '--resolveJsonModule' to import module with '.json' extension

当我尝试ng serve --resolveJsonModule 时,我得到了这个错误:Unknown option: '--resolveJsonModule'

我无法移动configuration.jsoncommon 目录与其他项目共享。

如何在 Angular 项目中导入本地 json 文件?

【问题讨论】:

  • 将你的 json 文件移动到 assets 目录。我遇到了同样的问题。
  • 我无法移动configuration.json,我编辑了我的问题。

标签: json angular typescript import


【解决方案1】:

如果您使用的是 typescript 2.9+ (Angular 6.1+),您可以导入 JSON 模块,以便将其编译到应用程序中。旧版本不支持此功能,因此可能是您的问题。

您需要做的就是确保在您的 tsconfig.json 中启用了以下三个编译器选项:

{
  ...
  "compilerOptions": {
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true
    ...
  }
}

然后你可以在任何 TS 文件中导入 JSON 模块:

import jsonContents from '../../contents.json';

【讨论】:

    【解决方案2】:

    我不太确定你的意思,但我猜你想在你的组件中使用配置值,对吧?

    根据tutorial,这可以通过在您的应用根文件夹中创建类型定义文件json-typings.d.ts 来解决,其中包含以下内容:

    declare module "*.json" {
       const value: any;
       export default value;
    }
    

    【讨论】:

    • 就我而言,这个选项解决了这个问题。不错!
    【解决方案3】:

    尝试使用 http 调用:

    this.http.get(`yourpath/..../common/configuration.json`).subscribe((resp: any) => {
       console.log(resp)
    });
    

    【讨论】:

    • 如果可能的话,我不想通过 http 公开我的 configuration.json 文件。
    • 如果是配置文件,最好放在environment.ts
    猜你喜欢
    • 1970-01-01
    • 2013-06-17
    • 2020-01-04
    • 1970-01-01
    • 2019-11-30
    • 2018-05-24
    相关资源
    最近更新 更多