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?
This question is related to
javascript
json
angular
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)
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);
})
}
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;
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;
. . . .
}
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"],
...
},
...
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
},
...
]
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);
}
}
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;
})
}
}
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";
import data from './data.json';
export class AppComponent {
json:any = data;
}
See this article for more details.
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>
Source: Stackoverflow.com