如何逐个发送值列表以调用单个方法

时间:2018-05-07 08:51:56

标签: angular typescript

这里我从服务器获取以下动态数据

try { .. } catch (e) { ... }

通过使用上面的数据,我在模板中循环,并在动态显示它

{
"Data": [
{
"LocationId": 6,
"LocationName": "J",
},
{
"LocationId": 3,
"LocationName": "M",

},
{
"LocationId": 2,
"LocationName": "P",
},
{
"LocationId": 5,
"LocationName": "B",
},
{
"LocationId": 4,
"LocationName": "D",

}
],
"ErrorCode": "201 - Success",
"Message": "Success",
"Status": true
}

这里我的问题是使用l​​ocationids值我怎么能在这里调用另一个服务/方法我有1,2,4,5,6作为locationids。在下面的服务中我只需要发送1个参数,所以我一次只能发送所有值并获得结果并显示在同一个div中

<div class="card"  *ngFor="let location of locationsName">
  <div class="card-body">
    <h5 class="card-title">{{location.LocationName |uppercase}}</h5>
    <h5 class="card-title" hidden>{{location.LocationId}}</h5>

  </div>

2 个答案:

答案 0 :(得分:0)

我同意之前关于不良做法的评论,您的后端应该返回所有需要的数据以提高性能。

但是,如果您无法更新后端,或者您有其他原因暗示来自UI的新调用,则应首先遍历locationsName数组,并在每次迭代时调用服务以获取数据。然后将它附加到迭代的当前对象。

locationsName数组的单个对象传递给服务:

for (var i = 0; i < this.locationsName.length; i++) {
   this.serv.getOrder(this.locationsName[i]).subscribe(res=>{
     // Here add new properties to objects
     this.locationsName[i]['OrdersData'] = res.Data;
   });
}

* ngFor项目将在从后端获取结果时更新,因为Angular触发器会自动更改检测。

答案 1 :(得分:0)

试试此代码

locationsName: any;
locationData: any;
locationsNameNew: any = [];
constructor() {
    this.locationsName = [
        {
            "LocationId": 6,
            "LocationName": "J",
        },
        {
            "LocationId": 3,
            "LocationName": "M",

        },
        {
            "LocationId": 2,
            "LocationName": "P",
        },
        {
            "LocationId": 5,
            "LocationName": "B",
        },
        {
            "LocationId": 4,
            "LocationName": "D",

        }
    ]
}

ngOnInit() {
    for (let locationsNameObj of this.locationsName) {
        var newValue = this.method1(locationsNameObj.LocationId);  // The service method which you want to call
        this.locationData = {
            'LocationId': locationsNameObj.LocationId,
            'LocationName': locationsNameObj.LocationName,
            'newLocationId': newValue
        };
        this.locationsNameNew.push(this.locationData); // New response Object
    }
}

public method1(LocationId: any) {
    var LocationIdDummy = LocationId+1;   // the new values which u obtained in Service
    return LocationIdDummy;
}

HTML代码

<div class="card"  *ngFor="let location of locationsNameNew">
  <div class="card-body">
    <h5 class="card-title">{{location.LocationName |uppercase}}</h5>
    <h5 class="card-title" hidden>{{location.LocationId}}</h5>
    <h5 class="card-title">{{location.newLocationId}}</h5>

  </div>