【问题标题】:Angular calling rest api infinitelyAngular无限调用rest api
【发布时间】:2018-09-20 12:45:27
【问题描述】:

使用 spring 作为后端。 目的是通过 id 获取图像并在页面中显示图像。

我正在从包含 json 样本的 rest api 接收 allItemsData

[
    {
        "id": 1,
        "itemTitle": "'title'",
        "itemDescription": "desccription",
        "userDetails": {
            "name": "adminnew",
            "email": "user2@gmail.com",
            "user_role_id": 1
        },
        "categoryId": 0,
        "imageDetailsList": [
            {
                "id": 87,
                "imageLocation": "C:\\imagePath\\faviconxR0.47460100811443706.ico"
            },
            {
                "id": 88,
                "imageLocation": "C:\\imagePath\\faviconxR0.47460100811443702.ico"
            }
        ]
    },....]

Angular 代码如下所示

<tr *ngFor="let data of allItemsData">
          <td>{{data.id}}</td>
          <td>{{data.itemTitle}}</td>
          <td>{{data.itemDescription}}</td>
          <td>{{data.userDetails.name}}</td>          
          <td>
            <table class='table table-striped'>
              <tr>
                <th>id</th>                
                <th>image</th>
                <th>imageLocation</th>
              </tr>
              <tr *ngFor="let imageData of data.imageDetailsList">
                <td>{{imageData.id}}</td>
                <td><img [src]="getImage(imageData.id)></td>
                <td>{{imageData.imageLocation}}</td>
              </tr>
            </table>
          </td>
        </tr>

当调用 getImageData() 时,客户端将执行 rest api 从基于 Spring 的服务器获取图像数据(Blob)。问题是图像 api 被无限调用。如果我在构造函数中执行 getImageData 它将只执行两次。

  1. 背后的原因是什么?
  2. 请提及任何其他替代角度方式或休息 api 设计

【问题讨论】:

  • 数据绑定就是这样工作的,它不断检查最新数据

标签: javascript spring angular


【解决方案1】:

下午好!

它的对象正在对数据数组中的每个迭代项调用getImageData()函数。

问题在于 Angular 会不断检查以检测更改,从而为用户更新信息。 contructor() 在组件初始化时运行,并且不会再次发生这种情况。

我的建议(因为我没有看到您的控制器)是:使用服务发出您的 API 请求,然后使用 RxJS 运算符正确填充图像。示例:

this.myService.getData().pipe(
    map(data => {
        data.imageDetailsList.map(item => {
            // item.id - Apply your logic to get the image correctly here, be sure to iterate a new array and return it so that the call returns the expected result.
        })
    })
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-23
    • 2019-05-30
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 2018-04-08
    • 2018-03-20
    • 2016-01-31
    相关资源
    最近更新 更多