【问题标题】:parse json to class object - angular 5将 json 解析为类对象 - 角度 5
【发布时间】:2018-04-23 06:52:37
【问题描述】:

我正在尝试将 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++) {
        ...
    }
}

它总是返回

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

【问题讨论】:

  • this.allResource = &gt;JSON.parse(... 语法无效。
  • 这是因为this.allResource 是在订阅中设置的。这意味着它是异步执行的。您的 for 循环在该订阅之外,这意味着它在设置 this.allResource 之前执行。另外,您可以使用 response.json() 代替 response.text(),它会自动为您解析,因此无需调用 JSON.parse

标签: javascript angular


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-07-27
    • 1970-01-01
    • 2020-05-08
    • 1970-01-01
    • 2021-10-14
    • 1970-01-01
    相关资源
    最近更新 更多