本文介绍了从Angular 2模板中未定义从http.get()加载的JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读取本地json文件,并将其解析为我制作的具有相同属性的类.当我尝试从该类中读取内容时,出现错误,提示该类为null或未定义.

I'm trying to read a local json file and parse it into a class that i made which have the same properties. When i try to read from the class, it gives me errors saying the class is null or undefined.

我有一个文件hall.ts,看起来像这样:

I have a file hall.ts which 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[]) {
    }
}

它使用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){}
}

我尝试从中读取的json文件hall1.json看起来像这样:

The json file, hall1.json, that i'm trying to read from looks like this:

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

我正在使用hall.service.ts尝试读取本地存储的json文件,并将其返回到Hall对象中.这是执行此操作的方法:

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. This is the methode for doing that:

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

到目前为止,它没有给我任何错误,但是当我尝试读取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

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

错误:

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

推荐答案

您必须记住http.get()调用是异步的.您的模板正在尝试将hall作为对象处理,然后再通过异步http调用解决.

You have to remember that the http.get() call is async. Your template is trying to process hall as an object before it has been resolved by your async http call.

这就是为什么未定义hall的原因,因此,您无法访问其上的任何属性(该属性尚不存在).

That's why hall is undefined and, therefore, you can't access any properties on it (it does not yet exist).

如Eric在评论中所述,请为您的模板尝试类似的操作:

As Eric mentioned in the comment, try something like this for your template:

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

这将使对hall上的naam的引用为空.

That will make the reference to naam on hall null safe.

更新:

为了完整起见,我将指出您实际上也可以使用* ngIf,尽管null安全检查可以使模板看起来更简洁.

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.

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

这篇关于从Angular 2模板中未定义从http.get()加载的JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 09:48