【问题标题】:Data not rendering on html but shows up on console log - Angular数据未在 html 上呈现,但显示在控制台日志中 - Angular
【发布时间】:2019-02-13 16:09:03
【问题描述】:

我可以从服务器端提取 JSON 数据并将其显示在控制台日志中,只是无法在 HTML 页面上呈现。可能是语法错误?

我正在尝试从我的 MongoDB 访问数据并通过 Angular 显示它。我已经从网络上添加了一些额外的选项来显示表格中的数据和过滤/排序/等...我确信这与我的*ngFor 有关。我试过 'let ticket of tickets.obj 和其他几个,没有运气。

我的 ts 文件。

this.http.post(environment.apiBaseUrl + '/filter', JSON.stringify(filterOptions), httpOptions)

.subscribe( res => {
  this.tickets = res;
  this.tickets = Array.of(this.tickets);
  this.totalPages = Math.ceil(this.totalRowCount / this.rowCount);
  console.log('Fetched Tickets');
  console.log(this.tickets);
},
  err => {
    console.log('Error fetching tickets');
  }
);

HTML

      <tbody>
        <tr *ngIf="tickets.length == 0">
          <td colspan="4" align="center" valign="middle">
            No Records Found.
          </td>
        </tr>
        <tr *ngFor="let ticket of tickets; let i = index;">
          <td>{{i+1+offset}}</td>
          <td>{{ticket.resolution}}</td>
          <td>{{ticket.ticketId}}</td>
          <td>{{ticket.status}}</td>
        </tr>
      </tbody>

表格是空白的。它应该有显示在控制台日志上的数据。

【问题讨论】:

  • 所以你的 this.http.post 正在返回数据?
  • 把你的循环改成这个*ngFor=let ticket of tickets[0].obj
  • this.tickets = res[0].obj; -> 无法读取未定义的属性“obj”| this.tickets = res.obj -> 属性 obj 不存在于类型 Object |对我有用的解决方案是更改票证 [0].obj 的 ngFor=let 票证。我永远不会想到这一点。谢谢大家的帮助。
  • Hameed,是的,它确实返回了数据。我知道,我从网上使用的示例使用 post 而不是 get。我认为这与服务器端的过滤有关(新手在这里只是我的最佳猜测)。

标签: angular typescript


【解决方案1】:

你要绑定的数组是结果数组元素中的obj属性。

这将有效:

...
  subscribe( res => {
  this.tickets = res[0].obj;
...

【讨论】:

    【解决方案2】:

    那里有一些问题: - 响应是数组,第一个元素是你需要的 您应该使用 this.tickets = res[0].obj。 希望我的回答能帮到你;)

    【讨论】:

      【解决方案3】:

      在您的 JSON 响应数组中存储在 obj 数组变量中,所以让它工作您的代码只需替换下面的代码就可以工作

      this.http.post(environment.apiBaseUrl + '/filter', JSON.stringify(filterOptions), httpOptions)
      
      .subscribe( res => {
        this.tickets = res.obj; //obj is array elements
         this.tickets = Array.of(this.tickets);
        this.totalPages = Math.ceil(this.totalRowCount / this.rowCount);
        console.log('Fetched Tickets');
        console.log(this.tickets);
      },
      
        err => {
          console.log('Error fetching tickets');
        }
      );
      

      希望这会有所帮助!

      【讨论】:

        猜你喜欢
        • 2019-04-11
        • 2022-08-03
        • 1970-01-01
        • 1970-01-01
        • 2022-01-16
        • 2015-03-31
        • 2015-05-11
        • 1970-01-01
        • 2019-06-10
        相关资源
        最近更新 更多