我正在尝试读取本地json文件并将其解析为我制作的具有相同属性的类.当我尝试从类中读取时,它给出了错误,表示该类为null或未定义.
我有一个文件hall.ts,看起来像这样:
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[]) { } }
它使用item.ts:
export class Item { constructor(public categorie:string,public productnummer:string,public omschrijving:string,public laatsteUitgevoerdeActie:Actie,public eerstVolgendeActie:Actie) { } } export class Actie{ constructor(datum: string,type: string,omschrijving: string){} }
我试图读取的json文件hall1.json看起来像这样:
{ "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","omschrijving": "inkt vervangen" } } ] }
我正在使用hall.service.ts尝试读取本地存储的json文件,并将其返回到Hall对象中.这是做到这一点的方法:
public getHall(): Observable<Hall> { return this.http.get('app/hall/hall1.json') .map((res:Response) => res.json()); }
我在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; }) } }
到目前为止,它没有给我任何错误,但是当我尝试从大厅对象中读取时,它是未定义的
@Component({ template: ` <div> {{hall.naam}} </div> ` })
错误:
EXCEPTION: TypeError: Cannot read property 'naam' of undefined in [ {{hall.naam}} in HallDetailComponent@1:7]
您必须记住http.get()调用是异步的.在您的异步http调用解析之前,您的模板正在尝试将大厅作为对象进行处理.
这就是为什么hall未定义,因此,您无法访问它上面的任何属性(它尚不存在).
正如Eric在评论中提到的那样,为你的模板尝试这样的事情:
@Component({ template: ` <div> {{hall?.naam}} <!-- note the added ? --> </div> ` })
这将使大厅null上的naam参考安全.
更新:
为了完整起见,我会指出你实际上也可以使用* ngIf,尽管null安全检查可以使模板看起来更整洁.
@Component({ template: ` <div *ngIf="hall"> <!-- note the added *ngIf --> {{hall.naam}} </div> ` })