Sto cercando di leggere un file json locale e di analizzarlo in una classe che ho creato che ha le stesse proprietà. Quando provo a leggere dalla classe, mi dà errori dicendo che la classe è nullo o indefinito.I dati JSON caricati da http.get() non sono definiti nel modello Angular 2
Ho un file hall.ts
che assomiglia a questo:
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[]) {
}
}
utilizza 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){}
}
Il file JSON, hall1.json
, che sto cercando di leggere da sguardi come questo:
{
"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"
}
}
]
}
Sto usando un hall.service.ts
h tenta di leggere il file json memorizzato localmente e lo restituisce in un oggetto Hall
. Questa è la methode per farlo:
public getHall(): Observable<Hall> {
return this.http.get('app/hall/hall1.json')
.map((res:Response) => res.json());
}
Io uso questo metodo nel mio 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;
})
}
}
Finora non mi dà errori, ma quando provo a leggere dall'oggetto hall
, si sais che non è definito
@Component({
template: `
<div>
{{hall.naam}}
</div>
`
})
Errore:
EXCEPTION: TypeError: Cannot read property 'naam' of undefined in [
{{hall.naam}}
in [email protected]:7]
hai provato a registrare il risultato.json() per vedere se stai effettivamente caricando il contenuto? – toskv
Dai un'occhiata [Elvis Operator] (https://angular.io/docs/ts/latest/guide/template-syntax.html) –