简体   繁体   English

在我的Angular 2模板中未定义从http.get()加载的JSON数据

[英]JSON data loaded from http.get() is undefined in my Angular 2 template

I'm trying to read a local json file and parse it into a class that i made which have the same properties. 我正在尝试读取本地json文件并将其解析为我制作的具有相同属性的类。 When i try to read from the class, it gives me errors saying the class is null or undefined. 当我尝试从类中读取时,它给出了错误,表示该类为null或未定义。

I have a file hall.ts which looks like this: 我有一个文件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[]) {
    }
}

It uses item.ts : 它使用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 , that i'm trying to read from looks like this: 我试图读取的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",
        "type": "vervanging",
        "omschrijving": "inkt vervangen"
      }
    }
  ]
}

I'm using a hall.service.ts which tries to read the json file which is locally stored, and returns it in an Hall object. 我正在使用hall.service.ts尝试读取本地存储的json文件,并将其返回到Hall对象中。 This is the methode for doing that: 这是这样做的方法:

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 我在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;
        })
    }
}

So far it doesn't give me any errors, but when i try to read from the hall object, it sais that it is undefined 到目前为止,它并没有给我任何错误,但是当我尝试从hall对象中读取时,它是未定义的

@Component({
    template: `
  <div>
    {{hall.naam}}
  </div>
  `
})

Error : 错误:

EXCEPTION: TypeError: Cannot read property 'naam' of undefined in [
    {{hall.naam}}
   in HallDetailComponent@1:7]

You have to remember that the http.get() call is async. 您必须记住http.get()调用是异步的。 Your template is trying to process hall as an object before it has been resolved by your async http call. 在您的异步http调用解析之前,您的模板正在尝试将hall作为对象进行处理。

That's why hall is undefined and, therefore, you can't access any properties on it (it does not yet exist). 这就是为什么hall未定义的原因,因此,您无法访问它上面的任何属性(它尚不存在)。

As Eric mentioned in the comment, try something like this for your template: 正如Eric在评论中提到的那样,为你的模板尝试这样的事情:

@Component({
    template: `
  <div>
    {{hall?.naam}}  <!-- note the added ? -->
  </div>
  `
})

That will make the reference to naam on hall null safe. 这将使hall null上的naam参考安全。

Update: 更新:

For the sake of completeness, I'll point out that you can actually use *ngIf for this as well, though the null safe check makes for a cleaner looking template. 为了完整起见,我会指出你实际上也可以使用* ngIf,尽管null安全检查可以使模板看起来更整洁。

@Component({
    template: `
  <div *ngIf="hall"> <!-- note the added *ngIf -->
    {{hall.naam}}
  </div>
  `
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM