【问题标题】:Angular - how to pass received JSON in to a html table?Angular - 如何将收到的 JSON 传递给 html 表?
【发布时间】:2019-12-26 23:19:42
【问题描述】:

我有一个 Angular 6 项目,我收到一个 JSON 对象,如下所示:

现在我想在 html 表上注入/传递它。这是我的代码:

界面

interface Ilivelog {
  instID: string;
  procID: string;
  threadNum: string;
  status: string;
}

对象

dataAgent: Ilivelog;

方法

onGetAgent() {
  this.backend.getAgentStatus().subscribe(
    (response: Response) => {
      this.dataAgent = response.json();
      console.log("Arrey Agent: " + this.dataAgent);
    },
    (error) => {
      console.log(error)
    }
  )
}

我如何获取数据

getAgentStatus() {
  return this.http.get('http://localhost:8081/rms_agent/status');
}

如何将这个 json 传递给 HTML 表格?

【问题讨论】:

    标签: html json angular typescript angular-material


    【解决方案1】:

    在你的组件模板中试试这个:

    <table border="1">
      <thead>
        <td>instID</td>
        <td>procID</td>
        <td>threadNum</td>
        <td>status</td>
      </thead>
      <tbody>
        <tr *ngFor="let item of dataAgent">
          <td>{{item.instID}}</td>
          <td>{{item.procID}}</td>
          <td>{{item.threadNum}}</td>
          <td>{{item.status}}</td>
        </tr>
      </tbody>
    </table>
    

    这里有一个Sample StackBlitz 供您参考。

    【讨论】:

    • 没有帮助,我只得到了thead。我相信这无法识别 item.body。
    • 它说:Arrey 代理:{"instID":"2018#11#06","procID":1161005,"threadNum":0,"status":9},{"instID" :"2018#11#06","procID":1161030,"threadNum":0,"status":9},{"instID":"2018#11#06","procID":1161020,"threadNum" :0,"状态":9}
    • 你能帮我吗?没有显示结果。还有我的日志: Arrey Agent: {"instID":"2018#11#06","procID":1161010,"threadNum":0,"status":9}
    • 会不会是我需要在后端使用httpClientModule之类的?
    • 从“@angular/http”导入 { Http };构造函数(私有 http: Http){ }
    【解决方案2】:

    首先检查 JSON 在验证器中是否有效。

    【讨论】:

    • 是的,这是主要问题,我的后端团队向我发送了一个字符串而不是 json...
    【解决方案3】:

    在您的 component.ts 中:

    results$: Observable<Ilivelog[]>;
    ngOnInit() {
       this.result$ = this.backend.getAgentStatus().pipe(
            map(res => res.json())
       );
    }
    

    在你的 view.html 中

    <table>
        <tr *ngFor="let log of (results$ | async)">
           <td>log.instID</td>
           <td>log.procID</td>
           <td>log.threadNum</td>
           <td>log.status</td>
        </tr>
    </table>
    

    【讨论】:

    • 未捕获错误:模板解析错误:无法绑定到“ngForIn”,因为它不是“tr”的已知属性。 ("
    • 然后它只显示:log.instID log.procID log.threadNum log.status
    • .pipe(map(res =&gt; res.json())); 应该在this.http.get() 之后而不是.subscribe()
    • 如果你看到 getAgentStatus() 返回一个 observable。但是如果你使用 HttpClient 模块,你不需要做 res.json()。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-01
    • 1970-01-01
    • 2018-11-25
    • 2018-04-09
    • 2021-08-11
    • 1970-01-01
    • 2014-08-11
    相关资源
    最近更新 更多