I'm trying to fetch data from a JSON File that I have in my assets folder in Angular 2, but it's not showing it. I want to get the data from the following JSON file:
test.json
[
"{'id': 1, 'building': 'Edificio 4', 'zone': 'Sin zonas', 'floor': 1, 'school': 1}",
"{'id': 2, 'building': 'Edificio 15', 'zone': 'Sin zonas', 'floor': 0, 'school': 1}",
"{'id': 3, 'building': 'Edificio 15', 'zone': 'Sin zonas', 'floor': 1, 'school': 1}",
"{'id': 4, 'building': 'Edificio 2', 'zone': 'C', 'floor': 2, 'school': 2}",
"{'id': 5, 'building': 'Edificio 2', 'zone': 'B', 'floor': 3, 'school': 2}",
"{'id': 6, 'building': 'Edificio 7', 'zone': 'J', 'floor': 7, 'school': 2}"
]
The component where I'm trying to do it is this one:
locker.component.ts
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
//this is the data class
class Place{
constructor(public id: string, public building: string, public zone: string, public floor: string, public school: string) { }
}
@Component({
selector: 'app-locker',
template: `
//here i have a template
`,
styleUrls: ['./locker.component.css'],
})
@Injectable()
export class LockerComponent implements OnInit {
places: Place[];
//if I manually add the data by hand here it works,
//I want to fetch the JSON data to this array
campus: String;
building: String;
floor: String;
zone: String;
type: String;
buildings = [];
floors = [];
zones = [];
types = [];
constructor(private http: HttpClient) {}
ngOnInit(): void {
this.http.get('./assets/test.json').subscribe(data => {
this.places = data;
});
}
}
I also have imported HttpClientModule in my app.component.ts as stated in https://angular.io/guide/http
I've read other stackoverflow answers to similar questions, but they don't seem to work, and answers are kind of blurry because they don't show all the code but only snippets.
Any ideas on why this is not working?
I also put here the function I'm using to show the data on one of the selects based on what I chose in the other:
onChangeCampus(event: any){
const campus = event.target.value;
this.buildings.length = 0;
this.floors.length = 0;
this.zones.length = 0;
this.types.length = 0;
for(let i of this.places){
if (i.school == campus && !(this.buildings.indexOf(i.building) > -1)){
this.buildings.push(i.building);
}
}
}
jsonfile so that we can help you