JSON解析返回{Object,Object}

时间:2016-08-14 20:55:21

标签: json angular typescript

我正在解析以下JSON,它应该通过promise返回Message []。它与HTTP文档中的Heroes示例项目中使用的代码相同

{
 "data": [
          {"id":"1","commid":"0","subject":"test1subject","body":"test1 body"},  
          {"id":"2","commid":"1","subject":"lkjhlkjh","body":"nbvjhg"}
 ]
}

而是返回带有对象的数据数组。我怎样才能让它像他们在例子中那样工作。它需要返回Message []

return this.http.get('messages.json')
                .toPromise()
                .then(this.extractData)
                .catch(this.handleError);

private extractData(res: Response) {
   let body = res.json();
   console.log(body);
   return body.data || { };
}

以下是我的组件中的代码

export class Message {
   id: number;
   commid: number; // community id that this msg belongs to
   subject: string;
   body: string;
}
   msgs:  Message[];
   this.msgService.getMessages().then(messages => {
       this.msgs = messages;
   });

这是角度doc示例: http://plnkr.co/edit/KZGeyULqrcuZDSeg0CkF?p=preview

1 个答案:

答案 0 :(得分:0)

我使用以下PHP返回我想要的内容:

$item_type = "data";
$rows = array('data' => array());
while($r = mysqli_fetch_assoc($result)) {
$rows['data'][] = $r;
}

echo json_encode($rows,JSON_NUMERIC_CHECK);