在 Angular 8 中动态加载 json

Load json dynamically in Angular 8

所以我必须从我的 Angular 8 应用程序的配置 json 文件中加载一个值。

一开始我是静态加载它的,所以当 js 被缩小时 - 来自 json 的未设置值被读取一次,再也不会读取。

然后我尝试像这样动态加载它:

app.component.ts:

ngOnInit(): void {
    let appInfo = "";
    import("../assets/config/config.json").then(config => {
       appInfo = config.appInfo;
    });
    //using appInfo here - empty string.
}

嗯,这也没有成功。它再次未设置。但它实际上存在于我的 config.json..

有人知道我可以尝试的另一种方法吗?

编辑:我想在 app.component.ts 的 ngOnInit 上访问它。 我的情况是,在应用程序启动之前,有人会更新 config.json 中的 appInfo 值。我想在启动时访问它。也感谢大家的建议,我会尝试并更新哪些有效。

**** 编辑:None 动态加载技术对我有用。尽管我尽了一切可能避免它,但我最终还是通过 http 调用完成了它。

在你的组件中像这样导入它。

import * as jsonData from '../assets/test.json';

然后

ngOnInit() {
  console.log(jsonData)
}

我可以像这样获取数据。

已更新

动态加载

  private jsonData;

  async ngOnInit() {
    await import("../assets/test.json").then(data => {
      this.jsonData = data;
    });

    console.log(this.jsonData);
  }

Working Demo

我刚刚通过使用命令 npm i --save-dev @types/node

安装 @types/node 尝试了一个 require 解决方案

然后将其添加到 tsconfig.app.json

"compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": ["googlemaps", "node"]
  }

然后 console.log(require("../assets/config/config.json")); 在某个地方它会被调用

然后用 ng serve 重新启动,它起作用了...

工作演示在此StackBlitz Live Demo

  • 您可以在 angular 中利用 rxjs。在这里,首先我们可以使用 import().
  • 获取 assets 文件夹中 json 文件的引用
  • fromPromise() 运算符正在将我们的导入 json 文件承诺转换为可观察的。这样将来如果 json 文件有任何更改,我们可以同时获得更改的值 [实时更新到模板 HTML 文件]。
  • 我们使用 async pipe 自动订阅 observable 和取消订阅 observable angular。

编辑

app.component.ts 是

  import {Observable} from 'rxjs';
  import { fromPromise } from 'rxjs/internal-compatibility';


  export class AppComponent  {
     dataJson: Observable<unknown>;
     dynamicallyLoadJsonFile = import('../assets/data.json');
     
     ngOnInit(){
         this.dataJson = fromPromise(this.dynamicallyLoadJsonFile);
     }
  }

app.component.html 是

<ng-container *ngIf="dataJson | async as data">
    <table class="table table-striped table-dark">
       <thead>
           <tr>
               <th scope="col">Id</th>
               <th scope="col">Name</th>
           </tr>
       </thead>
       <tbody>
           <tr *ngFor="let row of data['default'] ; let i=index">
               <td> {{row.id }} </td>
               <td> {{row.CarName}}</td>
           </tr>
       </tbody>
    </table>
</ng-container>

现在,在您的 json 文件表单资产文件夹中更新值后,所有更改都会自动反映在模板文件中,而无需再次重写..

 ngOnInit(): void {
    let appInfo = "";
    this.getDataHttp('../assets/config/config.json').subscribe(
      data => {
        var testResponse = data;
        console.log("I CANT SEE DATA HERE: ", testResponse);
      }
  )
}

get call for file, file can be any ware in other server or local

getDataHttp(url:string) {

    return this.http.get(url);
}

该通话的订阅

OR

you can also apply es 2020 dynamic import natively

var  moduleSpecifier = '../assets/config/config.json'
  import(moduleSpecifier).then((data) => {       
     let temp=data
    }).catch(error =>{debugger;alert(error.message)});