Load json dynamically in Angular 8

Viewed 7807

So I have to load a value from a configuration json file in my Angular 8 app.

In the beginning I was loading it statically and so when the js was minified - the unset value from the json was read once and never again.

Then I tried to load it dynamically like so:

app.component.ts:

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

Well that didn't work out either. Again it was unset. But it is actually present in my config.json..

Anyone have an idea on another approach I can try?

Edit: I want to access this on ngOnInit of my app.component.ts. My case is that before app startup someone will update the appInfo value in the config.json. I want to access it at startup. Also thank you all for the suggestions, I will try them out and update which ones work.

**** EDIT: None of the dynamic loading techniques worked for me. I ended up doing it with a http call although I tried all possible to avoid it.

4 Answers
 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);
}

subscription of that call

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)});

I just tried a require solution by installing @types/node with command npm i --save-dev @types/node

then added this to tsconfig.app.json

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

then had console.log(require("../assets/config/config.json")); somewhere where it would get called

then restarted with ng serve, and it worked...

in your component import it like this.

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

then

ngOnInit() {
  console.log(jsonData)
}

I am able to fetch data like this.

Updated

Dynamic Loading

  private jsonData;

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

    console.log(this.jsonData);
  }

Working Demo

Working Demo in this StackBlitz Live Demo

  • You can leverage use of rxjs in angular. Here, first of all we can get reference of json file in assets folder using import().
  • fromPromise() operator is converting our import json file promise into the observable. so that in future if anything is changed from json file we can get changed value at the same time [ Live Update To Template HTML file].
  • We use async pipe for subscribing observable and un-subscribing observable automatically by angular.

EDIT

app.component.ts is

  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 is

<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>

Now, after update value in your json file form assets folder all changes are automatically reflected in template file without having to re-write it again..

Related