Quick introduction blog on how to read json directly without http.get.
Angular 7 is based on TypeScript 3 which is good, because since version 2.9 TypeScript offers direct json import statements.
For more information on TypeScript 2.9 read the release notes: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html
Configuration
You need to prepare the application with additional flags in your tsconfig.json beforehand. To be more specific: you need to add additional compiler options:
- ResolveJSONModule
--resolveJsonModule
allows for importing, extracting types from .json files. - ESModuleInterop
--esModuleInterop
Allows default imports from modules with no default export. This is required since a .json file has no default output.
Example tsconfig.json:
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"module": "es2015",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"importHelpers": true,
"target": "es5",
"typeRoots": [
"node_modules/@types"
],
"lib": [
"es2018",
"dom"
],
"paths": {
"virtual-receipt-lib": [
"dist/virtual-receipt-lib"
],
"virtual-receipt-lib/*": [
"dist/virtual-receipt-lib/*"
]
},
"resolveJsonModule": true,
"esModuleInterop": true
}
}
If the tsconf.json is configured you are basically done and can import a .json file with a simple import-statement and without http.get, or other black magic.
Example
My .json file resides inside the /assets folder and its name is simply example.json:
{
"fruit": "Apple",
"size": "Large",
"color": "Red"
}
Inside a component, in my case the app.component.ts, you need to import the .json file:
import example from '../assets/example.json';
You can use it like you would use an object (in fact it is one):
constructor() {
console.log(example.fruit, example.color, example.size)
}
Result:
That’s it!
Keep it simple guys :)