Load json from local file with http.get() in angular 2
MY OWN SOLUTION
I created a new component
called test
in this folder:
I also created a mock called test.json
in the assests
folder created by angular cli
(important):
This mock looks like this:
[
{
"id": 1,
"name": "Item 1"
},
{
"id": 2,
"name": "Item 2"
},
{
"id": 3,
"name": "Item 3"
}
]
In the controller of my component test
import
follow rxjs
like this
import 'rxjs/add/operator/map'
This is important, because you have to map
your response
from the http get
call, so you get a json
and can loop it in your ngFor
. Here is my code how I load the mock data. I used http
get
and called my path to the mock with this path this.http.get("/assets/mock/test/test.json")
. After this i map
the response and subscribe
it. Then I assign it to my variable items
and loop it with ngFor
in my template
. I also export the type. Here is my whole controller code:
import { Component, OnInit } from "@angular/core";
import { Http, Response } from "@angular/http";
import 'rxjs/add/operator/map'
export type Item = { id: number, name: string };
@Component({
selector: "test",
templateUrl: "./test.component.html",
styleUrls: ["./test.component.scss"]
})
export class TestComponent implements OnInit {
items: Array<Item>;
constructor(private http: Http) {}
ngOnInit() {
this.http
.get("/assets/mock/test/test.json")
.map(data => data.json() as Array<Item>)
.subscribe(data => {
this.items = data;
console.log(data);
});
}
}
And my loop in it's template
:
<div *ngFor="let item of items">
{{item.name}}
</div>
It works as expected! I can now add more mock files in the assests folder and just change the path to get it as json
. Notice that you have also to import the HTTP
and Response
in your controller. The same in you app.module.ts (main) like this:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule, JsonpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { TestComponent } from './components/molecules/test/test.component';
@NgModule({
declarations: [
AppComponent,
TestComponent
],
imports: [
BrowserModule,
HttpModule,
JsonpModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Is it possible to retrieve a json data file with http.get() on stackblitz
Yes, it is possible.
Give the path direct from assets, like this -
this.httpClient.get('assets/data.json');
See the working example here
Even you can use same way on local also.
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);
});
}
}
Angular http.get doesn't work with local json file
If you are using the CLI, then you need to add the folder here:
"assets": [
"assets",
"api",
"favicon.ico"
],
This is part of the angular-cli.json
file.
angular2 serving local JSON file via http.get while having custom routing rules
copy your api folder into assets folder. Angular can only access files from assets
folder.
getAppointments() {
return this.http
.get('assets/api/mockAppointments.json')
.map((response : Response) => <Appointment[]>response.json().data)
.catch(this.handleError);
}
Angular 2 404 - Unable to read json file using http get
Out-of-the-box functionality of Angular projects built with the CLI allows for files to be publicly accessible via the assets folder located at /src/assets
. You can configure your project to allow other locations to be publicly accessible by editing the file angular-cli.json
. Find the line assets
and modify it in a way that allows access to the file(s) in question:
"assets": ["assets", "products.json","api/products.json"],
Hope that helps!
Related Topics
What Is "Function*" in JavaScript
Add St, Nd, Rd and Th (Ordinal) Suffix to a Number
Overriding a JavaScript Function While Referencing the Original
Difference Between Window.Location.Href=Window.Location.Href and Window.Location.Reload()
Array.Push() If Does Not Exist
How to Handle the 'Onkeypress' Event in Reactjs
Set Http Header for One Request
How to Simulate Key Presses or a Click with JavaScript
How to Pass the This Context to a Function
How to Solve 'Redirect Has Been Blocked by Cors Policy: No 'Access-Control-Allow-Origin' Header'
Make Checkbox Behave Like Radio Buttons with JavaScript
How to Filter Input Type="File" Dialog by Specific File Type
Trigger Autocomplete Without Submitting a Form
Screen Scraping from a Web Page with a Lot of JavaScript