0

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.

Tony Ngo
  • 19,166
  • 4
  • 38
  • 60
Sean
  • 332
  • 1
  • 6
  • 16
  • @dota2pro Yes, the problem is the compiled js file for aot does not have the import/require resolved... The build will complete but when I load the aot file i get that its not resolved: ERROR in ./dist/PROJECT/fesm5/LIBRARY.js Module not found: Error: Can't resolve '../../assets/file.json' in '/Users/ME/Projects/PROJECT/dist/LIBRARY/fesm5' – Sean May 12 '19 at 01:58

2 Answers2

0

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 
});
Mohamed Sweelam
  • 1,109
  • 8
  • 22
  • 1
    This happens in the component. I'm looking to import outside of the component.... – Sean May 12 '19 at 01:55
  • You can use wherever you want, it will be via injectable service, you need to adjust your service to return Observable, and subscribe on it anywhere. – Mohamed Sweelam May 12 '19 at 06:51
0

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");
    }
Angela Amarapala
  • 1,002
  • 10
  • 26