Angular 5 Service to read local .json file

JavascriptJsonAngular

Javascript Problem Overview


I am using Angular 5 and I've created a service using the angular-cli

What I want to do is to create a service that reads a local json file for Angular 5.

This is what I have ... I'm a bit stuck...

import { Injectable } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

@Injectable()
export class AppSettingsService {

  constructor(private http: HttpClientModule) {
    var obj;
    this.getJSON().subscribe(data => obj=data, error => console.log(error));
  }

  public getJSON(): Observable<any> {
    return this.http.get("./assets/mydata.json")
      .map((res:any) => res.json())
      .catch((error:any) => console.log(error));

  }

}

How can I get this finished?

Javascript Solutions


Solution 1 - Javascript

First You have to inject HttpClient and Not HttpClientModule, second thing you have to remove .map((res:any) => res.json()) you won't need it any more because the new HttpClient will give you the body of the response by default , finally make sure that you import HttpClientModule in your AppModule :

import { HttpClient } from '@angular/common/http'; 
import { Observable } from 'rxjs';

@Injectable()
export class AppSettingsService {

   constructor(private http: HttpClient) {
        this.getJSON().subscribe(data => {
            console.log(data);
        });
    }

    public getJSON(): Observable<any> {
        return this.http.get("./assets/mydata.json");
    }
}

to add this to your Component:

@Component({
    selector: 'mycmp',
    templateUrl: 'my.component.html',
    styleUrls: ['my.component.css']
})
export class MyComponent implements OnInit {
    constructor(
        private appSettingsService : AppSettingsService 
    ) { }

   ngOnInit(){
       this.appSettingsService.getJSON().subscribe(data => {
            console.log(data);
        });
   }
}

Solution 2 - Javascript

For Angular 7, I followed these steps to directly import json data:

In tsconfig.app.json:

add "resolveJsonModule": true in "compilerOptions"

In a service or component:

import * as exampleData from '../example.json';

And then

private example = exampleData;

Solution 3 - Javascript

You have an alternative solution, importing directly your json.

To compile, declare this module in your typings.d.ts file

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

In your code

import { data_json } from '../../path_of_your.json';

console.log(data_json)

Solution 4 - Javascript

I found this question when looking for a way to really read a local file instead of reading a file from the web server, which I'd rather call a "remote file".

Just call require:

const content = require('../../path_of_your.json');

The Angular-CLI source code inspired me: I found out that they include component templates by replacing the templateUrl property by template and the value by a require call to the actual HTML resource.

If you use the AOT compiler you have to add the node type definitons by adjusting tsconfig.app.json:

"compilerOptions": {
  "types": ["node"],
  ...
},
...

Solution 5 - Javascript

import data  from './data.json';
export class AppComponent  {
    json:any = data;
}

See this article for more details.

Solution 6 - Javascript

Assumes, you have a data.json file in the src/app folder of your project with the following values:

[    {        "id": 1,        "name": "Licensed Frozen Hat",        "description": "Incidunt et magni est ut.",        "price": "170.00",        "imageUrl": "https://source.unsplash.com/1600x900/?product",        "quantity": 56840    },    ...]

3 Methods for Reading Local JSON Files

Method 1: Reading Local JSON Files Using TypeScript 2.9+ import Statement

import { Component, OnInit } from '@angular/core';
import * as data from './data.json';

@Component({
  selector: 'app-root',
  template: `<ul>
      <li *ngFor="let product of products">

      </li>
  </ul>`,
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'Angular Example';

  products: any = (data as any).default;

  constructor(){}
  ngOnInit(){
    console.log(data);
  }
}

Method 2: Reading Local JSON Files Using Angular HttpClient

import { Component, OnInit } from '@angular/core';
import { HttpClient } from "@angular/common/http";


@Component({
  selector: 'app-root',
  template: `<ul>
      <li *ngFor="let product of products">

      </li>
  </ul>`,
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'Angular Example';
  products: any = [];

  constructor(private httpClient: HttpClient){}
  ngOnInit(){
    this.httpClient.get("assets/data.json").subscribe(data =>{
      console.log(data);
      this.products = data;
    })
  }
}

Method 3: Reading Local JSON Files in Offline Angular Apps Using ES6+ import Statement
If your Angular application goes offline, reading the JSON file with HttpClient will fail. In this case, we have one more method to import local JSON files using the ES6+ import statement which supports importing JSON files.

But first we need to add a typing file as follows:

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

Add this inside a new file json-typings.d.ts file in the src/app folder.

Now, you can import JSON files just like TypeScript 2.9+.

import * as data from "data.json";

Solution 7 - Javascript

Try This

Write code in your service

import {Observable, of} from 'rxjs';

import json file

import Product  from "./database/product.json";
    
getProduct(): Observable<any> {
   return of(Product).pipe(delay(1000));
}

In component

get_products(){
	this.sharedService.getProduct().subscribe(res=>{
		console.log(res);
	})        
}

Solution 8 - Javascript

Let’s create a JSON file, we name it navbar.json you can name it whatever you want!

navbar.json

[  {    "href": "#",    "text": "Home",	"icon": ""  },  {    "href": "#",    "text": "Bundles",    "icon": "",    "children": [      {        "href": "#national",        "text": "National",        "icon": "assets/images/national.svg"      }    ]
  }
]

Now we’ve created a JSON file with some menu data. We’ll go to app component file and paste the below code.

app.component.ts

import { Component } from '@angular/core';
import menudata from './navbar.json';

@Component({
  selector: 'lm-navbar',
  templateUrl: './navbar.component.html'
})
export class NavbarComponent {
	mainmenu:any = menudata;
	
}

Now your Angular 7 app is ready to serve the data from the local JSON file.

Go to app.component.html and paste the following code in it.

app.component.html

<ul class="navbar-nav ml-auto">
				  <li class="nav-item" *ngFor="let menu of mainmenu">
				  <a class="nav-link" href="{{menu.href}}">{{menu.icon}} {{menu.text}}</a>
				  <ul class="sub_menu" *ngIf="menu.children && menu.children.length > 0"> 
							<li *ngFor="let sub_menu of menu.children"><a class="nav-link" href="{{sub_menu.href}}"><img src="{{sub_menu.icon}}" class="nav-img" /> {{sub_menu.text}}</a></li> 
						</ul>
				  </li>
				  </ul>

Solution 9 - Javascript

Using Typescript 3.6.3, and Angular 6, none of these solutions worked for me.

What did work was to follow the tutorial here which says you need to add a small file called njson-typings.d.ts to your project, containing this:

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

Once this was done, I could simply import my hardcoded json data:

import employeeData from '../../assets/employees.json';

and use it in my component:

export class FetchDataComponent implements OnInit {
  public employees: Employee[];

  constructor() {
    //  Load the data from a hardcoded .json file
    this.employees = employeeData;
    . . . .
  }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser8770372View Question on Stackoverflow
Solution 1 - JavascriptEl houcine bougarfaouiView Answer on Stackoverflow
Solution 2 - JavascriptjaycerView Answer on Stackoverflow
Solution 3 - JavascriptNicolas Law-DuneView Answer on Stackoverflow
Solution 4 - JavascriptfishboneView Answer on Stackoverflow
Solution 5 - JavascriptOleView Answer on Stackoverflow
Solution 6 - JavascriptAbolfazlRView Answer on Stackoverflow
Solution 7 - Javascriptuser11426503View Answer on Stackoverflow
Solution 8 - JavascriptSurya R PraveenView Answer on Stackoverflow
Solution 9 - JavascriptMike GledhillView Answer on Stackoverflow