1

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);
      }
    }
  }
18
  • You have to import HttpClient Commented Dec 12, 2017 at 10:28
  • please share actualc json file so that we can help you Commented Dec 12, 2017 at 10:28
  • floor , school , id are int in json but you declare string in class Place Commented Dec 12, 2017 at 10:29
  • @Kyrsberg Importing HttpClient stops the error but the data is still not fetched, I'm using it for a dynamic form and it shows like an empty array. Commented Dec 12, 2017 at 10:32
  • @AddWebSolutionPvtLtd Editing right now Commented Dec 12, 2017 at 10:33

3 Answers 3

3

Just like Lucas aswered your first problem was with return value type

this.http.get<Place[]>('./assets/test.json').subscribe(data => {
   this.places = data;
 });

I believe you test.json format is little off too.

[
    "{'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}"
]

When it should be something like this. I removed the wrapping " marks and changed ' to " marks

[
  {"id": 1, "building": "Edificio4", "zone": "Sin zonas", "floor": 1, "school": 1},
  {"id": 2, "building": "Edificio15", "zone": "Sin zonas", "floor": 0, "school": 1},
  {"id": 3, "building": "Edificio15", "zone": "Sin zonas", "floor": 1, "school": 1},
  {"id": 4, "building": "Edificio2", "zone": "C", "floor": 2, "school": 2},
  {"id": 5, "building": "Edificio2", "zone": "B", "floor": 3, "school": 2},
  {"id": 6, "building": "Edificio7", "zone": "J", "floor": 7, "school": 2}
]
Sign up to request clarification or add additional context in comments.

1 Comment

One last question. In the end, I'm going to get the data from an API (the JSON is exactly the same, but instead of being in local storage, it is in an api). Will this work just by changing the url from './assets/test.json' to the URL of the REST API? @Kyrsberg
2

You should define the return value of the request:

 this.http.get<Place[]>('./assets/test.json').subscribe(data => {
   this.places = data;
 });

1 Comment

As in @Kyrsberg answer, this works as it doesn't show any compilation errors, but it is still not fetching the data I believe, because the form doesn't show anything.
2

You can call the json file through httpClient module by calling to :

getFile():Observable<Object>{
    return this.http.get('http://localhost:4200/assets/file.json');
}

and you have to keep the file in the assets folder so that you can access it . i hope that will help.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.