Angular 5 Service to read local .json file
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);
});
}
}
How to read local JSON file in an Angular Library?
Demo write one service to read json and you can use httpclient to reach json
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class JsonService {
constructor(private http: HttpClient) { }
getData(url): Observable<any> {
return this.http.get<any>(url);
}
}
then in component take from service
constructor(private json: JsonService ) {
json.getData('/url').subscribe((result)=> {
console.log(result)
});
}
Demo2
As a second way you can open "resolveJsonModule": true
in "compilerOptions"
and call in component like
import * as employeeData from "./test.json";
Angular 6 - Load JSON from local
The simplest solution:
import "myJSON" from "./myJson"
Important update!
I found, that this method stops working in newest Angular versions, because of this error:
ERROR in src/app/app.weather.service.ts(2,25): error TS2732: Cannot find module './data.json'. Consider using '--resolveJsonModule' to import module with '.json' extension
To make it works, go to the tsconfig.json and add this two, inside
compilerOptions( tsconfig.json ) :
"resolveJsonModule": true,
"esModuleInterop": true,
After change, re-run ng serve
.
If you only use the first option, you can get an error like this:
ERROR in src/app/app.weather.service.ts(2,8): error TS1192: Module '"....app/data/data.json"' has no default export.
(I found this very good answer here (https://www.angularjswiki.com/angular/how-to-read-local-json-files-in-angular/))
How do I read a local JSON file in Angular 12?
There are two additional things you need to do for Angular version 12.
First, you need to add some lines to the file. Reference this question here. NOTE: these are different than Angular version 11.
{
...
"compilerOptions": {
...
"resolveJsonModule": true, // add this line...
"esModuleInterop": true, // this line...
...
},
...
"allowSyntheticDefaultImports": true // and this line, notice this one is outside of "compiler options"
}
Second, you need to add a let
statement. The above didn't work for me alone, but by also taking this step, I got it to work. Reference this blog post.
The TypeScript file for my component: my-component.ts
...
import credentials from './config/credentials.json';
let my_username = credentials.username; // ADD THIS LINE
export class MyComponent implements OnInit {
...
// Properties
username: string = my_username; // NOW USE THE NEW VARIABLE
...
}
Admittedly I do not fully understand why this works, but it works. This source seems to suggest it has to do with variable scoping.
Read JSON file from file in Angular
You can use a quickfix provide by @amer-yousuf But it will also let you import any .js
file into your codebase as well. I wont prefer that. Here is an alternative approach
Define your config.json.ts
(notice it ends with .ts
and not .json
) something like below
export const CONFIG = { // your JSON is assigned to CONFIG variable
"say": "hello world"
}
In your other .ts
file where you want to use, use something like following code
import { CONFIG } from './config.json';
// ...
console.log(CONFIG.say);
// ...
Benefit of this method:
- You can still use tslint/eslint on config.json.ts
- Most editors will auto-complete for you
Unable to read json file in angular application using http client in cloud application
I found what was causing the issue. Server is not configured to handle or read JSON files. So I added created and added below code in web.config file under src folder. Issue is resolved.
web.config
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<system.webServer>
<staticContent>
<remove fileExtension=".json" />
<remove fileExtension=".woff" />
<remove fileExtension=".woff2" />
<mimeMap fileExtension=".json" mimeType="application/json" />
<mimeMap fileExtension=".woff" mimeType="application/font-woff" />
<mimeMap fileExtension=".woff2" mimeType="application/font-woff" />
</staticContent>
</system.webServer>
Related Topics
Variable Scope in D3 JavaScript
Chrome Extension - Sendresponse Not Waiting for Async Function
Difference Between JSON.Stringify and JSON.Parse
How to Do Associative Array/Hashing in JavaScript
Turning Off Eslint Rule for a Specific Line
Print Content of JavaScript Object
What's the Best Way to Break from Nested Loops in JavaScript
How to Get Notified About Changes of the History via History.Pushstate
How to Split a String into Segments of N Characters
How to Limit Google Autocomplete Results to City and Country Only
Multiple Left-Hand Assignment with JavaScript
Angularjs 1.2 $Injector:Modulerr
Sorting in JavaScript: Should Every Compare Function Have a "Return 0" Statement
Js:Convert Array of Strings to Array of Objects
Sort by Two Values Prioritizing on One of Them
Swap Rows with Columns (Transposition) of a Matrix in JavaScript