How to Load a JSON file in Angular2

Angular2 makes it very easy for us to load data from JSON files, we can do it by simply making a http request. Now let’s see how we can do that.

To be able to make Http requests we first have to import the HttpModule on the app.module.ts, once you’ve done that your code should look like this:

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule }      from '@angular/http';
import { AppComponent }   from './app.component';
 
@NgModule({
  imports:      [ BrowserModule, HttpModule ],
  declarations: [ AppComponent],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Next you have put your JSON file in a location accessible via Http, you can put it directly on the root folder of your project if you want, I’m going to create a new folder called /data to keep the files organized.

Now you can load you file using http.get() like I did in the constructor:

import {Http} from '@angular/http';
import { Component } from '@angular/core';
 
@Component({
  selector: 'my-app',
  template: ``,
})
export class AppComponent { 
 
    data;
 
    constructor(private http:Http) {
        this.http.get('data/data.json')
                .subscribe(res => this.data = res.json());
    }
 
}

Note that I’ve used the subscribe() function here, it receives another function responsible for handling the response, in this case I’m just assigning it the the data variable.

Very simple, right? I’ve used Angular 2.0.0-rc.6 version for this tutorial, if you are using a different version this may not work for you.

Recommended for you

2 comments on “How to Load a JSON file in Angular2

  1. Gaurav Pandvia

    Hi,
    I am trying to load a json file ussing http.get request but I am getting 404 not found for that json file . My json file is in this kind of folder structure is /src/app/app1/component1/data.json. My component or module file from where I am making the call is also in the same folder and I have tried providing the following path also but it still fails . Also I have set in the head. Can that be a problem?
    Please help , stuck on this for a long time now.

Leave a Reply to Max Cancel reply

Your email address will not be published. Required fields are marked *

Obs: Use the tag <pre lang="LANGUAGE"> to include code blocks to your comment.
Example: <pre lang="javascript"> console.log('Test'); </pre>