尝试以角度对对象数组进行迭代

问题描述 投票:1回答:1

问题:尝试迭代有角度的对象数组,但仅出现第一个对象。该服务有效,我得到了完整的答复。

我为所有资产执行获取的角度服务:

getAsset(asset_type):Observable<Asset[]>{

      return this.http.get<Asset[]>(`${this.find}/${this.domain_id}/assets?asset_type=${asset_type}`, httpOptions);
    }

资产的型号

export class Asset{
    asset_name: string;
    mac_address: string;
    floor: number;
    location: string;
    temperature: number;
    battery: number;
    timestamp_tlm: string;
    timestamp_geo: string;
}

我在其中调用服务并发送相应参数的component.ts。

ngOnInit() {
    this.whereisService.getAsset(this.asset_type).subscribe(assets => {

      if(Array.isArray(assets)){
        this.assets = assets;
      }
      else if(typeof assets === 'string' ){
        this.assets = [];
      }
      else{
         this.assets = [assets];
      }


   });
  }
}

component.html

<div class="text-center">
    <ul id="ticket" class="list-unstyled my-2">
        <li class="btn w-100 bg-primary text-center text-white mx-0 my-2 display-block" *ngFor="let asset of rows_transformed let i = index">       
            <p class="h5"> Name: {{ asset?.asset_name }}</p>
            <p class="h5"> Tipo: {{ asset?.asset_type }}</p>
            <p class="h5"> Mac adress: {{ asset?.mac_address }}  </p>
            <p class="h5"> Piso: {{ asset?.floor }} </p>
            <p class="h5"> Localização: {{ asset?.location }} </p>
            <p class="h5"> Hora: {{ asset?.timestamp_tlm }} </p>
        </li>
    </ul>
</div>

从API响应JSON

{
    "code": 200,
    "data": [
        {
            "mac_address": "AC233F52BD17",
            "floor": -3,
            "asset_name": "Tripés microfone 1",
            "asset_type": "Carro trasnporte",
            "location": "Armazem 2",
            "temperature": 22.0,
            "battery": 74.0,
            "timestamp_tlm": "2019-11-22 10:17:49.563121+00:00",
            "timestamp_geo": "2019-11-22 10:17:49.563266+00:00"
        },{...}
    ]
}
arrays json angular object service
1个回答
0
投票

JSON响应与您的期望不符。首先简化您的组件。该服务应该返回Observable<Asset[]>。因此,该组件不应进行测试以查看所允许的偶数是数组还是字符串。应该是一系列资产。如果不是,则应该修复该服务:

this.whereisService.getAsset(this.asset_type).subscribe(assets => this.assets = assets);

然后,您需要修复服务。服务器返回的是数组。这是一个具有data属性的对象,该属性是一组资产。所以服务应该是

getAsset(asset_type): Observable<Asset[]>{
  return this.http.get<{ data; Asset[]; }>(`${this.find}/${this.domain_id}/assets?asset_type=${asset_type}`, httpOptions).pipe(
    map(object => object.data)
  );
}

最后,由于数组是在属性assets中而不是在rows_transformed中,因此模板应该遍历该数组:

*ngFor="let asset of assets; index as i"

0
投票

使用

*ngFor="let asset of assets" 

在您的HTML中,而不是rows_transformed。您也可以报废我,因为您不使用它。

© www.soinside.com 2019 - 2024. All rights reserved.