Angular4: how to access local json?

In Angular2, you can have a folder / data / and a json file, and you can access it at localhost: 4200 / data / something.json.

This is not possible in Angular4.

Any ideas how to make it work?

+13
json javascript angular
source share
7 answers

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 also

also see changlog of angle-cli for the way

+8
source share

Of course it is possible. Suppose this is your json file

enter image description here


And here is your code to call 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; }); } } 
+7
source share

I ran into the same problem when my Observable Angular service was in the src / app / 'folder and it was trying to load a local JSON file. I tried to put the JSON file in the same application folder, in the new "api" folder, use different types of relatives / absolute routes, but this did not help, and I got 404 error. The moment I put it in the folder " assets "... BAM !!! it worked. I think there is something else ...

Maybe this link helps ...

COMPONENT RELATIVE WAYS IN EFFORTS

+7
source share

You can also use "require",

 let test = require('./test.json'); 
+7
source share

Based on this post , here is the complete answer for Angular 6+:

From an angular-cli document, json can be viewed as assets and accessed from standard imports without using an ajax request.

Suppose you added your json files to the "your-json-dir" directory:

  1. add "your-json-dir" to the angular.json file (:

    "assets": [ "src/assets", "src/your-json-dir" ]

  2. allow import of json modules into the typings.d.ts file to prevent typewriting errors:

    declare module "*.json" { const value: any; export default value; }

  3. in your controller / service / anything else file just import the file using this relative path:

    import * as myJson from 'your-json-dir/your-json-file.json';

+2
source share

I get it.

In Angular2, I had a folder under the src folder. In Angular4, you should have it in the root folder.

Example:

Angular2:

root / src / data / file.json

Angular4:

root / data / file.json

0
source share

You can add the location of your folder in the Assets tag in angular.json

 "assets": [ "src/favicon.ico", "src/assets", "src/api" ], 
0
source share

All Articles