简体   繁体   中英

Can't import local json file in angular 5

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM