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.
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.
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));
}
}
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);
}
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.
In Angular 5
you can just say
this.http.get<Example>('assets/example.json')
This will give you Observable<Example>
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!
You need to make an HTTP call to your games.json
to retrieve it.
Something like:
this.http.get(./app/resources/games.json).map
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
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
},
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With