I am trying to load a local JSONfile of two ways.
This is my json file:
{
"imgsesion": "fa_closesesion.png",
"texthome": "volver a la home",
"logo": "fa_logo.png",
"menu": {
"background": "orange",
"link1": "ESCRITOR",
"link2": "MÚSICO",
"link3": "AYUDA ADMIN",
"submenu": {
"link1": {
"text1": "novelas",
"text2": "obras de teatro"
},
"link2": {
"text1": "compositor",
"text2": "intérprete"
}
}
}
}
- Way 1: Using Http
This is my service file (general.service.ts)
getContentJSON() {
return this.http.get('assets/json/general.json')
.map(response => response.json());
}
This way working ok, but shows the next error in the web browser console:
ERROR TypeError: Cannot read property 'menu' of undefined
- Way 2: Using HttpClient
This is my service file (general.service.ts)
getContentJSON() {
return this.httpClient.get("assets/json/general.json");
}
It does not work because I can not find the general.json file, it goes through the control of the error and it gives me an error 404
This is the component file (app.component.ts)
export class AppComponent implements OnInit {
contentGeneral: any;
ngOnInit() {
this.getContentJSON();
}
getContentJSON() {
this.generalService.getContentJSON().subscribe(data => {
this.contentGeneral = data;
}, // Bind to view
err => {
// Log errors if any
console.log('error: ', err);
});
}
}
This is the template file (app.component.html
):
<a href="#" routerLink="/home" class="linkHome">{{contentGeneral.texthome}}</a>
<div class="submenu" *ngIf="linkWrite.isActive || isSubMenuWriter">
<span class="d-block text-right small">{{contentGeneral.menu.submenu.link1.text1}}</span>
<span class="d-block text-right small">{{contentGeneral.menu.submenu.link1.text2}}</span>
</div>
This is my actual error:
In app.component.ts, I add the import:
import * as data_json from './assets/json/general.json';
But when I launch ng serve it gives me the following error:
How I could resolve it?