Angular 2 - Load JSON Data

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.

  1. export interface IArticle  
  2. {  
  3.     Id: number;  
  4.     title: string;  
  5.     summary: string;  
  6. // This is just a sample script. Paste your real code (javascript or HTML) here.  
  7. if ('this_is' == /an_example/) {  
  8.     of_beautifier();  
  9. else {  
  10.     var a = b ? (c % d) : e[f];  
  11. }   

 Now, add a demo JSON file and add some data.

  1. [{  
  2.     "id""1",  
  3.     "title""Angular 2 - Getting Started",  
  4.     "summary""In this article, you will learn how to start working with Angular 2."  
  5. }, {  
  6.     "id""2",  
  7.     "title""Show data using Angular 2",  
  8.     "summary""In this article, you will learn how to display data using Angular 2."  
  9. }, {  
  10.     "id""3",  
  11.     "title""Cascading DropDown In Angular 2",  
  12.     "summary""In this article, you will learn how to use cascading DropDownList using Angular 2."  
  13. }, {  
  14.     "id""4",  
  15.     "title""Show data using Web API and Service in Angular 2",  
  16.     "summary""In this article, you will learn how to bind data with observable and display using service and Web API in Angular 2."  
  17. }, {  
  18.     "id""5",  
  19.     "title""Angular 2 - File Upload using Web API",  
  20.     "summary""In this article, you will learn how to File Upload using Web API in Angular 2."  
  21. }]   

 Now, add a new service TypeScript file and locate JSON file path and make a new function to get the articles list.

  1. import {  
  2.     Injectable  
  3. } from '@angular/core';  
  4. import {  
  5.     Http,  
  6.     Headers,  
  7.     RequestOptions,  
  8.     Response  
  9. } from '@angular/http';  
  10. import {  
  11.     Observable,  
  12.     Subject  
  13. } from 'rxjs/Rx';  
  14. import 'rxjs/Rx'//get everything from Rx    
  15. import 'rxjs/add/operator/toPromise';  
  16. import {  
  17.     IArticle  
  18. } from './article';  
  19. @Injectable()  
  20. export class ArticleService {  
  21.     private jsonFileURL: string = "./app/jsondata/article.json";  
  22.     constructor(private http: Http) {}  
  23.     //    
  24.     getArticles(): Observable < IArticle[] > {  
  25.         return this.http.get(this.jsonFileURL).map((response: Response) => {  
  26.             return <IArticle[] > response.json()  
  27.         }).catch(this.handleError);  
  28.     }  
  29.     //    
  30.     private handleError(errorResponse: Response) {  
  31.         console.log(errorResponse.statusText);  
  32.         return Observable.throw(errorResponse.json().error || "Server error");  
  33.     }  
  34. }  

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.

  1. import {  
  2.     Http  
  3. } from '@angular/http';  
  4. import {  
  5.     Component,  
  6.     OnInit  
  7. } from '@angular/core';  
  8. import {  
  9.     ArticleService  
  10. } from './shared/articleservice';  
  11. import {  
  12.     Observable  
  13. } from 'rxjs/Rx';  
  14. import {  
  15.     IArticle  
  16. } from './shared/article';  
  17. @Component({  
  18.     selector: 'my-app',  
  19.     templateUrl: './app/app.component.html',  
  20.     styleUrls: ['./app/styles/styles.css']  
  21. })  
  22. export class AppComponent implements OnInit {  
  23.     title = 'Top 5 Articles';  
  24.     articles: IArticle[];  
  25.     errorMessage: string;  
  26.     ///    
  27.     constructor(private _articleService: ArticleService) {  
  28.         this.articles = [];  
  29.     }  
  30.     ///    
  31.     ngOnInit(): void {  
  32.         let self = this;  
  33.         self._articleService.getArticles().subscribe(response => this.articles = response, error => this.errorMessage = < any > error);  
  34.     }  
  35. }  

Here is my HTML page design with styles.

  1. <div>  
  2.     <div class="page-header">  
  3.         <h1>{{title}}</h1>  
  4.     </div>  
  5.     <div class="list-group" *ngFor="let article of articles">  
  6.         <a href="#" class="list-group-item active">  
  7.             <h4 class="list-group-item-heading">{{article.title}}</h4>  
  8.             <p class="list-group-item-text">{{article.summary}}</p>  
  9.         </a>  
  10.     </div>  
  11. </div>  

Now, let’s work on Index.html page and add node_modules references and styles file; and add component selector name.

  1. <!DOCTYPE html>  
  2. <html>  
  3.   
  4. <head>  
  5.     <title></title>  
  6.     <meta charset="utf-8" />  
  7.     <meta name="viewport" content="width=device-width, initial-scale=1">  
  8.     <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />  
  9.     <link href="app/styles/styles.css" rel="stylesheet" />  
  10.     <!-- Polyfill(s) for older browsers -->  
  11.     <script src="node_modules/core-js/client/shim.min.js"></script>  
  12.     <script src="node_modules/zone.js/dist/zone.js"></script>  
  13.     <script src="node_modules/reflect-metadata/Reflect.js"></script>  
  14.     <script src="node_modules/systemjs/dist/system.src.js"></script>  
  15.     <!-- Configure SystemJS -->  
  16.     <script src="systemjs.config.js"></script>  
  17.     <script>  
  18.         System.import('app').catch(function(err) {  
  19.             console.error(err);  
  20.         });  
  21.     </script>  
  22. </head>  
  23.   
  24. <body>  
  25.     <header class="navbar navbar-inner navbar-fixed-top">  
  26.         <nav class="container">  
  27.             <div class="navbar-header"> <span class="app-title">Load JSON in Angular 2</span> </div>  
  28.         </nav>  
  29.     </header>  
  30.     <main class="container">  
  31.         <my-app>Loading...</my-app>  
  32.     </main>  
  33. </body>  
  34.   
  35. </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.

Up Next
    Ebook Download
    View all
    Learn
    View all