简体   繁体   English

将json解析为类对象-angular 5

[英]parse json to class object - angular 5

I'm trying to parse JSON into a class object but it returns always an error. 我正在尝试将JSON解析为类对象,但它始终返回错误。

JSON string - this is what i got in allResourceString 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"
  },
  ...
]

class: 类:

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

parse JSON: 解析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++) {
        ...
    }
}

It's always return 总是回来

ERROR TypeError: Cannot read property 'length' of undefined at HomeComponent.ngOnInit (home.component.ts:35) 错误TypeError:无法读取HomeComponent.ngOnInit上未定义的属性'length'(home.component.ts:35)

httpGet returns an Observer, and subscribing to an Observer is an asynchronous method. httpGet返回一个Observer,而订阅Observer是一个异步方法。 Async means that the code will bypass that function's execution and move to the next code, and run the callback functions defined in it once your HTTP request is finished. 异步意味着代码将绕过该函数的执行并移至下一个代码,并在您的HTTP请求完成后运行其中定义的回调函数。

You need to take your for loop below it and put it in the success callback. 您需要将其for循环置于其下方,并将其放入成功回调中。

parse JSON: 解析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),
    );    

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

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