Angular4: how do access local json?

You can use "require" too;

let test = require('./test.json');

I was facing the same issue, where my Observable Angular service was located at inside 'src/app/' folder and it was trying to load a local JSON file. I tried to put the JSON file inside the same app folder, inside a new 'api' folder, used various kinds of relatives/absolute routes, but it didn't help and I got 404 error. The moment I put it inside 'assets' folder, it worked. I guess there is more to it?

Maybe this link helps:

COMPONENT-RELATIVE PATHS IN ANGULAR


you can use this code

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

     }
}

here file.json is your local json file.

see here also

  • How to get a json file in angular2 using the Http class

also see the changlog of angular-cli for path

  • https://github.com/angular/angular-cli/blob/master/CHANGELOG.md#100-rc4-2017-03-20

Ofcourse its possible. Let's assume here is your json file

enter image description here


And here is your code to call the json

import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map'

@Injectable()
export class YourService {

   constructor(private http: Http) { }

   getAdvantageData(){
      let apiUrl = './assets/data/api/advantage.json';
      return this.http.get(apiUrl)
      .map( (response: Response) => {
         const data = response.json();
         return data;
      });
   }  
}