解析Angular2中的JSON响应

时间:2017-06-08 00:18:47

标签: json angular angular-datatables

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

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

以下是我的HTML文件 -

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

“userList”保存我的json响应。

问题: - 我收到错误“错误尝试差异'[{"id":1,"firstName":"Foo","lastName":"Bar"},{"id":2,"firstName":"Happy","lastName":"Kid"}]'。只允许数组和可迭代”。

如何将我的json解析为我所需的ui?

3 个答案:

答案 0 :(得分:1)

ngFor期望它可以迭代结果的数组或对象,但根据你的问题,它们都不存在。

尝试使用此代码 -

对于GET请求 -

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

对于POST请求 -

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

这将返回Json响应以进行迭代。

  

注意 -

     

这是伪代码,根据您的要求进行修改。

答案 1 :(得分:0)

你JSON无效。试着保持

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

如果您想将密钥保存为字符串,则需要编写要转换的管道。

答案 2 :(得分:0)

在这种情况下你得到的json只是一个字符串,而不是一个javascript数组。 public static async void sendFileToUser(long tgId, int fileId) { ExceptionDispatchInfo capturedException = null; String occuredException = ""; try { string pathPhysical1 = (string)myHT[fileId]; string fileName = fileId + ".pdf"; var fs = new MemoryStream(File.ReadAllBytes(pathPhysical1)); FileToSend streamFile = new FileToSend(fileName, fs); await Bot.SendDocumentAsync(tgId, streamFile, "file sended", false); await Bot.SendChatActionAsync(tgId, ChatAction.UploadDocument); } } catch (System.Net.Http.HttpRequestException ex) { capturedException = ExceptionDispatchInfo.Capture(ex); occuredException = "System.Net.Http.HttpRequestException"; } catch (ApiRequestException ex) { capturedException = ExceptionDispatchInfo.Capture(ex); occuredException = "ApiRequestException"; } catch (TaskCanceledException ex) { capturedException = ExceptionDispatchInfo.Capture(ex); occuredException = "TaskCanceledException"; } catch (Exception ex) { occuredException = "Exception"; capturedException = ExceptionDispatchInfo.Capture(ex); } if (capturedException != null) { printExceptionINConsole(capturedException.SourceException, "capturedException-" + occuredException); } } 期望一个数组迭代,但提供的参数是一个字符串。您需要使用响应上的ngFor方法将字符串转换为javascript对象。

示例代码:

json()

如果您直接使用observable并且不转换return this.http.get("some-api-url") .toPromise() .then(response => response.json().data); // check this line ,那么您需要在响应上调用toPromise方法。您甚至可以使用本机json()方法将字符串响应转换为javascript对象。