Before moving ahead, I would recommend you read my previous articles which explain how to install npm and add other mandatory files.
Getting Started
- Start Visual Studio.
- Create a new website.
- Provide the name and the location of the website.
- Click "Next".
After adding all mandatory Angular 2 files, add a new TypeScript file.
- export interface IArticle
- {
- Id: number;
- title: string;
- summary: string;
- }
- if ('this_is' == /an_example/) {
- of_beautifier();
- } else {
- var a = b ? (c % d) : e[f];
- }
Now, add a demo JSON file and add some data.
- [{
- "id": "1",
- "title": "Angular 2 - Getting Started",
- "summary": "In this article, you will learn how to start working with Angular 2."
- }, {
- "id": "2",
- "title": "Show data using Angular 2",
- "summary": "In this article, you will learn how to display data using Angular 2."
- }, {
- "id": "3",
- "title": "Cascading DropDown In Angular 2",
- "summary": "In this article, you will learn how to use cascading DropDownList using Angular 2."
- }, {
- "id": "4",
- "title": "Show data using Web API and Service in Angular 2",
- "summary": "In this article, you will learn how to bind data with observable and display using service and Web API in Angular 2."
- }, {
- "id": "5",
- "title": "Angular 2 - File Upload using Web API",
- "summary": "In this article, you will learn how to File Upload using Web API in Angular 2."
- }]
Now, add a new service TypeScript file and locate JSON file path and make a new function to get the articles list.
- import {
- Injectable
- } from '@angular/core';
- import {
- Http,
- Headers,
- RequestOptions,
- Response
- } from '@angular/http';
- import {
- Observable,
- Subject
- } from 'rxjs/Rx';
- import 'rxjs/Rx';
- import 'rxjs/add/operator/toPromise';
- import {
- IArticle
- } from './article';
- @Injectable()
- export class ArticleService {
- private jsonFileURL: string = "./app/jsondata/article.json";
- constructor(private http: Http) {}
-
- getArticles(): Observable < IArticle[] > {
- return this.http.get(this.jsonFileURL).map((response: Response) => {
- return <IArticle[] > response.json()
- }).catch(this.handleError);
- }
-
- private handleError(errorResponse: Response) {
- console.log(errorResponse.statusText);
- return Observable.throw(errorResponse.json().error || "Server error");
- }
- }
Now, add a new component file and provide appropriate name, selector name, templateURL and styleURLs, service reference, and other TypeScript file references. After that, make a service object in constructor and call service function on ngOnInit event.
- import {
- Http
- } from '@angular/http';
- import {
- Component,
- OnInit
- } from '@angular/core';
- import {
- ArticleService
- } from './shared/articleservice';
- import {
- Observable
- } from 'rxjs/Rx';
- import {
- IArticle
- } from './shared/article';
- @Component({
- selector: 'my-app',
- templateUrl: './app/app.component.html',
- styleUrls: ['./app/styles/styles.css']
- })
- export class AppComponent implements OnInit {
- title = 'Top 5 Articles';
- articles: IArticle[];
- errorMessage: string;
-
- constructor(private _articleService: ArticleService) {
- this.articles = [];
- }
-
- ngOnInit(): void {
- let self = this;
- self._articleService.getArticles().subscribe(response => this.articles = response, error => this.errorMessage = < any > error);
- }
- }
Here is my HTML page design with styles.
- <div>
- <div class="page-header">
- <h1>{{title}}</h1>
- </div>
- <div class="list-group" *ngFor="let article of articles">
- <a href="#" class="list-group-item active">
- <h4 class="list-group-item-heading">{{article.title}}</h4>
- <p class="list-group-item-text">{{article.summary}}</p>
- </a>
- </div>
- </div>
Now, let’s work on Index.html page and add node_modules references and styles file; and add component selector name.
- <!DOCTYPE html>
- <html>
-
- <head>
- <title></title>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
- <link href="app/styles/styles.css" rel="stylesheet" />
- <!-- 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>
- <!-- Configure SystemJS -->
- <script src="systemjs.config.js"></script>
- <script>
- System.import('app').catch(function(err) {
- console.error(err);
- });
- </script>
- </head>
-
- <body>
- <header class="navbar navbar-inner navbar-fixed-top">
- <nav class="container">
- <div class="navbar-header"> <span class="app-title">Load JSON in Angular 2</span> </div>
- </nav>
- </header>
- <main class="container">
- <my-app>Loading...</my-app>
- </main>
- </body>
-
- </html>
Everything is done here. Now, run the application to see the output.
![]()
Conclusion
In this article, we have seen how to load JSON file in Angular 2. If you have questions or comments, drop me a line in comments section.