I am building a map application using Angular Maps and want to import a JSON file as a list of markers defining locations. I'm hoping to use this JSON file as marker[] array inside the app.component.ts . Instead of defining a hardcoded array of markers inside the TypeScript file.
What is the best process of importing this JSON file for use in my project? Any direction greatly appreciated!
As of Typescript 2.9, one can simply add:
to the
tsconfig.json
. Thereafter, it's easy to use a json file (and there will be nice type inference in VSCode, too):data.json
:In your Typescript file:
import { cases } from './data.json';
Here is complete answer for Angular 6+ based on @ryanrain answer:
From angular-cli doc, json can be considered as assets and accessed from standard import without use of ajax request.
Let's suppose you add your json files into "your-json-dir" directory:
add "your-json-dir" into angular.json file (:
"assets": [ "src/assets", "src/your-json-dir" ]
create or edit typings.d.ts file (at your project root) and add the following content:
declare module "*.json" { const value: any; export default value; }
This will allow import of ".json" modules without typescript error.
in your controller/service/anything else file, simply import the file by using this relative path:
import * as myJson from 'your-json-dir/your-json-file.json';
I had read some of the responses and they didn't seem to work for me. I am using Typescript 2.9.2, Angular 6 and trying to import JSON in a Jasmine Unit Test. This is what did the trick for me.
Add:
To
tsconfig.json
Import like:
Stop
ng test
, start again.Reference: https://blogs.msdn.microsoft.com/typescript/2018/05/31/announcing-typescript-2-9/#json-imports
First solution - simply change the extension of your .json file to .ts and add
export default
at the beginning of the file, like so:Then you can just simply import the file without the need to add typings, like so:
Second solution get the json via HttpClient.
Inject HttpClient into your component, like so:
and then use this code:
https://angular.io/guide/http
This solution has one clear adventage over other solutions provided here - it doesn't require you to rebuild entire application if your json will change (it's loaded dynamically from a separate file, so you can modify only that file).
As stated in this reddit post, after Angular 7, you can simplify things to these 2 steps:
compilerOptions
in yourtsconfig.json
file:And that's it. You can now use
myData
in your components/services.