简体   繁体   中英

Import Json file in Angular 6?

Tried several different ways to import a json file but get

countries.json has unknown extension.

Is there a solution to this I'm missing?

Current tsconfig:

  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,    
    "module": "es2015",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "types": [ "node"],
    
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  },
  "include": ["./src/**/*", "./src/**/*.json"],

}

Here the import is as follows import * as countries from './countries.json';

And the setup of countries.json is this..

   [
    {"name": "Afghanistan", "code": "AF"},
    {"name": "Åland Islands", "code": "AX"},
    ]

I believe Angular 6 json support is a bit wonky, so I would update the proyect to a newer version (which, with angular, is not a huge workload). From Angular 7 onwards you can configure your tsconfig.json file like this:

{
  "compileOnSave": false,
  "compilerOptions": {
    ...
    "resolveJsonModule": true,
    ...
}

This way you can import your.json files normally like this:

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

Hope this helps!

Ill leave an article with an example an step by step: https://www.techiediaries.com/import-local-json-files-in-typescript/

import something from "somewhere" means that import the default exported value from path.

Clearly, json files does not have any export as default. You can import everything or you can import some property from it.

To import everything from json file:

import * as something from "somewhere"

To import some property from json file: when the content of file is like

file.json

{
    "name": "Stackoverflow",
    "otherProperty": "otherValue"
}

To import only name :

import { name } from "file.json"

But Typescript added --resolvejsonmodule option in the version 2.9 . As I know Angular started to use Typescript 2.9 at the version 7 , so for your case:

json.service.ts

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


  getJson(path: string) {
    return this.http.get(path);
  }
}

and do not forget to add your JsonService to providers array of your module and finally, you need to import HttpClientModule at your module.

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