Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Angular2中解析JSON响应_Json_Angular_Angular Datatables - Fatal编程技术网

在Angular2中解析JSON响应

在Angular2中解析JSON响应,json,angular,angular-datatables,Json,Angular,Angular Datatables,我从后端获得的json是[{“id”:1,“firstName”:“Foo”,“lastName”:“Bar”},{“id”:2,“firstName”:“Happy”,“lastName”:“Kid”}]。 下面是我的HTML文件- Id FirstName LastName Action 1. Foo Bar Edit 2. Happy Kid Edit 身份证件 名字 姓 行动 {{user.firstName} 编辑 “userL

我从后端获得的json
[{“id”:1,“firstName”:“Foo”,“lastName”:“Bar”},{“id”:2,“firstName”:“Happy”,“lastName”:“Kid”}]。

下面是我的HTML文件-

Id  FirstName LastName  Action
1.  Foo       Bar       Edit
2.  Happy     Kid       Edit

身份证件
名字
姓
行动
{{user.firstName}
编辑
“userList”保存着我的json响应

问题:-我收到错误“尝试区分”
[{“id”:1,“firstName”:“Foo”,“lastName”:“Bar”},{“id”:2,“firstName”:“Happy”,“lastName”:“Kid”}]
”。只允许数组和iterables。“


如何将json解析到所需的ui中?

您的json无效。努力保持

<table datatable class="row-border hover">
  <thead>
    <tr>
      <th>ID</th>
      <th>First name</th>
      <th>Last name</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>

    <tr *ngIf="userList" >
      <td *ngFor="let user of userList">{{user.firstName}}</td>

      <td>
        <button>Edit</button>
      </td>
    </tr>
    </tbody>
</table>    

如果希望将键保留为字符串,则需要编写管道进行转换。

在本例中,您得到的json只是一个字符串,而不是javascript数组
ngFor
需要迭代数组,但提供的参数是字符串。您需要使用响应上的
json()
方法将字符串转换为javascript对象

示例代码:

[{id:1,firstName:"Foo",lastName:"Bar"},{id:2,firstName:"Happy",lastName:"Kid"}]

如果您直接使用Observable,而不是将
转换为promise
,那么即使这样,您也需要在响应上调用
json()
方法。您甚至可以使用本机的
JSON.parse
方法将字符串响应转换为javascript对象。

ngFor
需要可以迭代结果的数组或对象,但根据您的问题,它们都不存在

尝试使用此代码-

获取请求- 邮寄申请- 这将为迭代返回Json响应

注- 这是一个伪代码,根据您的要求进行修改


你确定你的列表叫itemList而不是userList吗?我打错了。。。我的列表是“用户列表”!!!它现在工作吗?你确定
userList
是一个数组吗?似乎它可能是一个未解析的字符串。您在何处以及如何创建它?JSON有什么是无效的?
return this.http.get("some-api-url")
                .toPromise()
                .then(response => response.json().data); // check this line
return this.http.get(API_URL)
        .map(res => res.json()
        .subscribe(
            data => this.YOUR_VARIABLE = JSON.stringify(data),
            error => alert(error),
            () => TO_DO_AFTER_REQUEST_COMPLETION
         ));
return this.http.post(API_URL,POST_PARAMETERS,{
            headers:HEADERS
        })
        .map(res => res.json()
        .subscribe(
            data => this.YOUR_VARIABLE = JSON.stringify(data),
            error => alert(error),
            () => TO_DO_AFTER_REQUEST_COMPLETION
         ));