40

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.

2

12 Answers 12

62

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));

     }
}
Sign up to request clarification or add additional context in comments.

6 Comments

In the catch statement, you probably ought to return the error since you are logging it in the constructor, right?
PS: sometimes if json is not valid than you have to use res.text() instead of res.json() at the time of .map
@Jeff console.log returns undefined and also logs the error. This was useful in my case. @Pardeep like I said this was the solution for my case, but your contribution may help other people. Thanks.
Do we need to define .json file in app.module.ts file also? it is throwing me error as ` localhost:4201/file.json` not found.Can you suggest for this. I mean on localhost it is not able to find file.json as it is not deployed .
@PrasannaSasne If you are using angular-cli, you can move your file to assets folder and then call the get function as assets/file.json it might work. If you post a separate question I can show the configuration of angular-cli to use files from another file.
|
39

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);
} 

2 Comments

I created another folder and tried to access the file but it didn't work. only way it worked on keeping json file in the assets folder. Not sure why it's working like that.
Because your component folders can only have four types of files: 1) '.html' 2) '.css' or '.scss' 3) '.spec.ts' 4) and your 'component.ts' file. Other then these four types you cannot add any other types, like .json. Other types like images, eg: .png, .jpeg or .json need to be kept outside 'app' folder.
11

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.

Comments

8

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!

11 Comments

I have tried this solution but I sitll get a module error, am I missing something?
@RossRawlins, what error are you getting and from which line?
Cannot find module '../../../../assets/countries' as soon as I try to build it. Is it the path to the file? I cant tell...
@RossRawlins, I'm not sure but it look like a reference error. I personally prefer to start each path with a "./" (so the path is relative to the current file and not to the project root). You can try to create a new empty .js file (or any other that doesn't need a loader) in the same location as the .json, and try to reference it. If you still getting an error then this is a reference issue and not an error with the json-loader. If the reference is correct you'll need to provide more information about your issue.
Best answer so far, clear, precise and easy solution. Thank you @Gil Epshtain!
|
7

In Angular 5

you can just say

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

This will give you Observable<Example>

Comments

6

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

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

2 Comments

Files in <yourproject>/src/app/xy.json are found in this.http.get(./app/xy.json)
@yonexbat...It depends on location of ts file you are writing this code. This is not always true...
3

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

Comments

2

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
    },

Comments

1
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)
}
}

Comments

0

Without using HttpClientModule you can use require method in order to import your local json file.

const jsonFile = require("../assets/sidemenu-route.json");

Then you just need to convert it into json

 ngOnInit(): void {
   this.sideMenuList = JSON.parse(JSON.stringify(jsonFile));
  }

Hope it works!

Comments

-1

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

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

Comments

-1

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

1 Comment

Please add some explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.