I'm trying to import a local file to use the data in it. I have tried the require method and the import method. Neither seems to work. I'm using Angular 5 and Typescript 2.9.2. I am locked to angular 5. I'm building for aot and when I look at the fesm5 file that gets exported the json file does not seem to resolve. (I DO NOT WANT TO PULL IT IN WITH HTTP...)

import * as data from '../../assets/file.json';

When I try to set tsconfig value to:

 "resolveJsonModule": true,

I get an error on build:

 Cannot read property 'slice' of undefined
 TypeError: Cannot read property 'slice' of undefined
at addReferencesToSourceFile (/Users/ME/Projects/PROJECT/node_modules/@angular/compiler-cli/src/transformers/compiler_host.js:520:54)
at TsCompilerAotCompilerTypeCheckHostAdapter.getSourceFile (/Users/ME/Projects/PROJECT/node_modules/@angular/compiler-cli/src/transformers/compiler_host.js:348:13)

I have also tried the:

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

This doesn't seem to help at all.

Also tried:

declare function require(url: string);

var data = require('../../assets/file.json');

This does not seem to resolve the json in the final file either.

3 Answers

0
Mohamed Sweelam On

You can put your file under assets folder and get it using HTTP GET from HttpClient module, this will return the whole json file, use your file path in your GET request URL; something like this:

this.http.get('../assets/file.json')
    .subscribe(jsonFormat => { 
      //Your code 
});
0
Community On

You need to read the json file content using http So first you need to create a service to fetch the json content

    import { HttpClient } from '@angular/common/http'; 
    import { Observable } from 'rxjs/Observable';
    import { Injectable } from "@angular/core";

    @Injectable()
    export class JsonSettingService {
      constructor(private http: HttpClient) {
      }

       public getJsonData(): Observable<any> {
        return this.http.get("./assets/jsonFile.json");
      }
    }

Then inject your service into your component

    export class MyComponent implements OnInit {
        constructor(
            private jsonSettingService : JsonSettingService  
        ) { }

       ngOnInit(){
           this.jsonSettingService.getJsonData().subscribe(data => {
                console.log(data);
            });
       }
    }

Please let me know if you need any help.

0
Angela Amarapala On

You can create a service for all the GET, POST, PUT& DELETE implementations. Then in your GET method of HttpClient that is imported from ‘@angular/common/http’, call the JSON with the link to your local JSON file.

    public getAbout(): Observable<any> {
        return this.http.get("./assets/json/about.json");
    }