[json] How to fetch JSON file in Angular 2

as I am new to the Angular, can anyone please give a simple solution on loading the JSON file data using angular 2.

My code is like below

Index.html

_x000D_
_x000D_
<html>_x000D_
  <head>_x000D_
    <title>Angular 2 QuickStart</title>_x000D_
    <meta charset="UTF-8">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
    <link rel="stylesheet" href="css/styles.css">_x000D_
    <!-- 1. Load libraries -->_x000D_
     <!-- Polyfill(s) for older browsers -->_x000D_
    <script src="node_modules/core-js/client/shim.min.js"></script>_x000D_
    <script src="node_modules/zone.js/dist/zone.js"></script>_x000D_
    <script src="node_modules/reflect-metadata/Reflect.js"></script>_x000D_
    <script src="node_modules/systemjs/dist/system.src.js"></script>_x000D_
    <!-- 2. Configure SystemJS -->_x000D_
    <script src="systemjs.config.js"></script>_x000D_
    <script>_x000D_
      System.import('app').catch(function(err){ console.error(err); });_x000D_
    </script>_x000D_
  </head>_x000D_
  <!-- 3. Display the application -->_x000D_
  <body>_x000D_
    <my-app>Loading...</my-app>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

app.component.ts

_x000D_
_x000D_
import {Component} from '@angular/core';_x000D_
  _x000D_
@Component({_x000D_
  selector: 'my-app',_x000D_
  template: `_x000D_
          <div id="main">_x000D_
            Main Div_x000D_
               <div id = "header"></div>_x000D_
               <div id = "content">_x000D_
                  <ul class="games">_x000D_
                      <li>_x000D_
           _x000D_
                      </li>_x000D_
                  </ul>_x000D_
               </div>_x000D_
          </div>_x000D_
     `_x000D_
})_x000D_
export class AppComponent {_x000D_
 }
_x000D_
_x000D_
_x000D_

games.json

_x000D_
_x000D_
{_x000D_
 "games":[_x000D_
  {_x000D_
   "title":"Primary Operations",_x000D_
   "enabled":true_x000D_
  },_x000D_
  {_x000D_
   "title":"Curated Games",_x000D_
   "enabled":false_x000D_
  }_x000D_
 ]_x000D_
}
_x000D_
_x000D_
_x000D_

I want to fetch all games from games.json into li at app.component.ts Please advise in detail.

This question is related to json angular

The answer is


You don't need HttpClient, you don't even need Angular. All you need is WebPack and JSON-Loader, both are already part of Angular-CLI.

All the code you need is this line:

import * as someName from './somePath/someFile.json;

And the your json-data can be found under someName.default. However this code will throw a type-error from the TypeScript compiler - this isn't a real error, but only a type-error.

To solve it add this code to your src/typings.d.ts file (if it doesn't exist create it):

declare module "*.json"
{
  const value: any;
  export default value;
}

Please notice: that working in this method will compile your json (minify/uglify) into the app bundle at build time. This mean that you won't need to wait until this file will load - as you will if you choice to work with httpClient.get(...) - meaning faster application!


i think the assets folder is public, you can access it directly on the browser

http://localhost:4020/assets/

unlike other privates folders, drop your json file in the assets folder


For example, in your component before you declare your @Component

const en = require('../assets/en.json');

I needed to load the settings file synchronously, and this was my solution:

export function InitConfig(config: AppConfig) { return () => config.load(); }

import { Injectable } from '@angular/core';

@Injectable()
export class AppConfig {
    Settings: ISettings;

    constructor() { }

    load() {
        return new Promise((resolve) => {
            this.Settings = this.httpGet('assets/clientsettings.json');
            resolve(true);
        });
    }

    httpGet(theUrl): ISettings {
        const xmlHttp = new XMLHttpRequest();
        xmlHttp.open( 'GET', theUrl, false ); // false for synchronous request
        xmlHttp.send( null );
        return JSON.parse(xmlHttp.responseText);
    }
}

This is then provided as a app_initializer which is loaded before the rest of the application.

app.module.ts

{
      provide: APP_INITIALIZER,
      useFactory: InitConfig,
      deps: [AppConfig],
      multi: true
    },

If you using angular-cli Keep the json file inside Assets folder (parallel to app dir) directory

return this.http.get('<json file path inside assets folder>.json'))
    .map((response: Response) => {
        console.log("mock data" + response.json());
        return response.json();
    }
    )
    .catch(this.handleError);
}

Note: here you only need to give path inside assets folder like assets/json/oldjson.json then you need to write path like /json/oldjson.json

If you using webpack then you need to follow above same structure inside public folder its similar like assets folder.


service.service.ts
--------------------------------------------------------------

import { Injectable } from '@angular/core';
import { Http,Response} from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';

@Injectable({
  providedIn: 'root'
})
export class ServiceService {
 private url="some URL";

constructor(private http:Http) { }     

//getData() is a method to fetch the data from web api or json file

getData(){
           getData(){
          return this.http.get(this.url)
            .map((response:Response)=>response.json())
        }
          }
}






display.component.ts
--------------------------------------------

//In this component get the data using suscribe() and store it in local object as dataObject and display the data in display.component.html like {{dataObject .propertyName}}.

import { Component, OnInit } from '@angular/core';
import { ServiceService } from 'src/app/service.service';

@Component({
  selector: 'app-display',
  templateUrl: './display.component.html',
  styleUrls: ['./display.component.css']
})
export class DisplayComponent implements OnInit {
      dataObject :any={};
constructor(private service:ServiceService) { }

  ngOnInit() {
    this.service.getData()
      .subscribe(resData=>this.dataObject =resData)
}
}

_x000D_
_x000D_
public init() {_x000D_
    return from(_x000D_
      fetch("assets/server-config.json").then(response => {_x000D_
        return response.json();_x000D_
      })_x000D_
    )_x000D_
      .pipe(_x000D_
        map(config => {_x000D_
          return config;_x000D_
        })_x000D_
      )_x000D_
      .toPromise();_x000D_
  }
_x000D_
_x000D_
_x000D_


Keep the json file in Assets (parallel to app dir) directory

Note that if you would have generated with ng new YourAppname- this assets directory exists same line with 'app' directory, and services should be child directory of app directory. May look like as below:

::app/services/myservice.ts

getOrderSummary(): Observable {
    // get users from api
    return this.http.get('assets/ordersummary.json')//, options)
        .map((response: Response) => {
            console.log("mock data" + response.json());
            return response.json();
        }
    )
    .catch(this.handleError);
} 

In Angular 5

you can just say

this.http.get<Example>('assets/example.json')

This will give you Observable<Example>


You need to make an HTTP call to your games.json to retrieve it. Something like:

this.http.get(./app/resources/games.json).map