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

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:

    .subscribe(jsonFormat => { 
      //Your code 
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";

    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 {
            private jsonSettingService : JsonSettingService  
        ) { }

           this.jsonSettingService.getJsonData().subscribe(data => {

Please let me know if you need any help.

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