将json解析为类对象 - angular 5

时间:2018-04-22 20:33:03

标签: javascript angular

我试图将JSON解析为类对象,但它总是返回错误。

JSON字符串 - 这是我在allResourceString

中得到的
[  
  {  
    "resourceName":"12 strong",
    "resourceType":"Movie",
    "summary":"12 Strong tells the story of the first Special Forces team deployed to Afghanistan after 9/11; under the leadership of a new captain, the team must work with an Afghan warlord to take down for the Taliban.",
    "director":"Nicolai Fuglsig",
    "length":130,
    "yearDate":2018,
    "uploadDate":"2018-04-20T21:00:00.000Z",
    "totalGrade":0,
    "img":"XkFtZTgwNjY2NDczNDM@._V1_SY1000_CR0,0,674,1000_AL_.jpg",
    "genre":"Action,Drama,History"
  },
  ...
]

类:

export class Resource {

    public resourceName: string;
    public resourceType: string;
    public summary: string;
    public director: string;
    public length: number;
    public yearDate: number;
    public uploadDate: Date;
    public totalGrade: number;
    public img: string;
    public genre: string;
}

解析JSON:

 allResource: Array<Resource>;
 i: number;

  constructor(private httpService: HttpService) { }

  ngOnInit() {
    this.httpService.httpGet('')
      .subscribe(
      (response) => {
        this.allResourceString = response.text();
        this.allResource = <Array<Resource>>JSON.parse(this.allResourceString);
      },
      (error) => console.log(error),
    );    

    for (this.i = 0; this.i < this.allResource.length; this.i++) {
        ...
    }
}

它总是返回

  

错误类型错误:无法读取属性&#39;长度&#39;未定义的       在HomeComponent.ngOnInit(home.component.ts:35)

1 个答案:

答案 0 :(得分:0)

httpGet返回一个Observer,订阅一个Observer是一个异步方法。异步意味着代码将绕过该函数的执行并转移到下一个代码,并在HTTP请求完成后运行其中定义的回调函数。

你需要在它下面使用你的for循环并把它放在成功的回调中。

解析JSON:

ngOnInit() {
    this.httpService.httpGet('')
      .subscribe(
      (response) => {
        this.allResourceString = response.text();
        this.allResource = <Array<Resource>>JSON.parse(this.allResourceString);

        for (this.i = 0; this.i < this.allResource.length; this.i++) {
        ...
        }
      },
      (error) => console.log(error),
    );