angular - 无法将 JSON 数组获取到 HTML 动态表,并且在 Angular 中使用 typescript 显示空白

标签 angular typescript

我刚刚在谷歌上搜索并找到了很多资源来将动态数据添加到 HTML 文件中,但我应用了大部分资源,但到目前为止没有任何帮助。

我刚刚在 app.component.html 文件中添加了以下几行。我可以在 html 页面上看到标题,但我找不到值,它显示为空白,我在 Chrome 控制台页面中没有找到任何错误消息。

app.component.html:

<table width="100%" class="table">
  <thead>
     <tr>
      <th> Product Name</th>
      <th> API Name </th>
      <th>Message</th>
     </tr>
  </thead>
  <tbody>
     <tr *ngFor="let binary of data">
       <td>{{binary.productName}}</td>
       <td>{{binary.apiName}}</td>
       <td>{{binary.message}}</td>
     </tr>
  </tbody>
   </table>

app.component.ts:

 getById():void {
    const url:any = "http://localhost:8081/api/products?productId=23421342221";       
    this.http.get(url).subscribe(data =>{ 
        console.log(data);
    });  
  }

上面的代码在控制台打印一个合适的值,如下所示:

enter image description here

示例 JSON 数组如下所示(虚拟 JSON 模型):

{
 "dataSet":[
            { 
              "productName": "mobile", 
              "apiName":"Android",
              "message":"Its android mobile device and model is sony m5"
            },
            {
              "productName": "Laptop", 
              "apiName":"Linux",
              "message":"It's linux OS and kernel version is <XXX>"
            }
         ]
 }

有人可以帮助我了解我在代码中遗漏了什么以及为什么它没有显示出来。如果您能帮助我理解其中的逻辑,那就太好了,这样对我以后的引用很有帮助。

提前致谢。

最佳答案

您需要访问datadataSet数组

将您的代码更改为

this.http.get(url).subscribe(data =>{ 
       this.data = data.dataSet;
}); 

关于angular - 无法将 JSON 数组获取到 HTML 动态表,并且在 Angular 中使用 typescript 显示空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59434425/

相关文章:

javascript - SvelteKit - "ReferenceError: File is not defined"

angular - 具有名称的表单控件没有值访问器...用于垫选择控件

angular - Ionic 2 自定义后退按钮操作

Angular 2 为多个模块定义数据模型

Angular 7 Route 动画在嵌套路由器 socket 中不起作用

angular - ListDetailsPage 是 2 个模块的一部分,请将 ListDetailsPage 移动到导入 AppModule 和 ListDetailsPageModule 的更高模块

angular - Sentry 附加数据

reactjs - React 和 Typescript,Axios 响应的类型?

javascript - 动态创建带有嵌套对象/数组结构的数组的更好方法

javascript - 将字符串中的数组转换为数组