I am trying to read a local json file and parse it in a class that I created with the same properties. When I try to read from a class, it gives me errors saying the class is null or undefined.
I have a hall.ts file that looks like this:
import {Item} from '../item/item'; export class Hall { constructor(public id:number, public naam:string, public oppervlakte:number, public aantalItems:number, public itemsMetNodigeActie:number, public items:Item[]) { } }
It uses item.ts :
export class Item { constructor(public categorie:string, public naam:string, public productnummer:string, public omschrijving:string, public laatsteUitgevoerdeActie:Actie, public eerstVolgendeActie:Actie) { } } export class Actie{ constructor(datum: string, type: string, omschrijving: string){} }
The json file, hall1.json , which I am trying to read, is as follows:
{ "id": 1, "naam": "hall1", "oppervlakte": 100, "aantalItems": 3, "itemsMetNodigeActie": 3, "items": [ { "id": 1, "categorie": "machine", "productnummer": "ADE124e", "omschrijving": "print papieren af", "laatsteUitgevoerdeActie": { "datum": "2015-01-05T00:00:00.000Z", "type": "vervanging", "omschrijving": "papier vervangen" }, "eerstVolgendeActie": { "datum": "2016-01-06T00:00:00.000Z", "type": "vervanging", "omschrijving": "inkt vervangen" } } ] }
I use hall.service.ts , which tries to read a json file that is locally stored, and returns it in the Hall object. This is the method to do this:
public getHall(): Observable<Hall> { return this.http.get('app/hall/hall1.json') .map((res:Response) => res.json()); }
I use this method in my hallDetail.component.ts
export class HallDetailComponent implements OnInit{ public hall: Hall; constructor( private service: HallService ){} ngOnInit(){ this.service.getHall().subscribe((hall:Hall) => { this.hall = hall; }) } }
While this does not give me any errors, but when I try to read from the Hall object, it means that it is undefined
@Component({ template: ` <div> {{hall.naam}} </div> ` })
Mistake:
EXCEPTION: TypeError: Cannot read property 'naam' of undefined in [ {{hall.naam}} in HallDetailComponent@1 :7]