Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch JSON file in Angular 2

Tags:

json

angular

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

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

app.component.ts

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

games.json

{
	"games":[
		{
			"title":"Primary Operations",
			"enabled":true
		},
		{
			"title":"Curated Games",
			"enabled":false
		}
	]
}

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

like image 740
Vishu Avatar asked Sep 09 '16 07:09

Vishu


People also ask

What is JSON file in angular?

A file named angular. json at the root level of an Angular workspace provides workspace-wide and project-specific configuration defaults for build and development tools provided by the Angular CLI. Path values given in the configuration are relative to the root workspace folder.


9 Answers

Here is a part of my code that parse JSON, it may be helpful for you:

import { Component, Input } from '@angular/core';
import { Injectable }     from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable()
export class AppServices{

    constructor(private http: Http) {
         var obj;
         this.getJSON().subscribe(data => obj=data, error => console.log(error));
    }

    public getJSON(): Observable<any> {
         return this.http.get("./file.json")
                         .map((res:any) => res.json())
                         .catch((error:any) => console.log(error));

     }
}
like image 179
Bünyamin Sarıgül Avatar answered Oct 13 '22 01:10

Bünyamin Sarıgül


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);
} 
like image 40
HydTechie Avatar answered Oct 12 '22 23:10

HydTechie


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.

like image 44
Vijay Gajera Avatar answered Oct 13 '22 01:10

Vijay Gajera


In Angular 5

you can just say

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

This will give you Observable<Example>

like image 36
Jana Avatar answered Oct 12 '22 23:10

Jana


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!

like image 25
Gil Epshtain Avatar answered Oct 12 '22 23:10

Gil Epshtain


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

this.http.get(./app/resources/games.json).map
like image 22
John Baird Avatar answered Oct 12 '22 23:10

John Baird


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

like image 33
Anthony Agbator Avatar answered Oct 13 '22 00:10

Anthony Agbator


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
    },
like image 21
jonas Avatar answered Oct 12 '22 23:10

jonas


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)
}
}
like image 40
Raviraj S Kharvi Avatar answered Oct 13 '22 01:10

Raviraj S Kharvi