Angular 4 - 将一个新项目从一个可观察的数据推送到一个数组

时间:2017-06-09 07:37:13

标签: javascript arrays angular typescript observable

我有一个页面,其中显示包含locations的列表,然后点击其中的每个列表,我为assets显示location。我已经设置了这样的模板:

<li
    *ngFor="let location of locations"
    (click)="select(location)"
    droppable
    [dragOverClass]="'drag-target-border'"
    (onDrop)="onItemDrop($event, location)"
    >
      {{ location.name }}
      <ul *ngIf="currentLocation == location && assetsVisible">
        <ng-container *ngIf="currentLocation.assets?.length > 0;else message">
          <li
            *ngFor="let asset of currentLocation.assets"
            class="asset"
            draggable
            [dragData]="asset"
            >
            <p>{{ asset.title }}</p>
            <p>{{ asset.address }}</p>
            <p>{{ asset.value }}</p>
          </li>
        </ng-container>
        <ng-template #message>No assets for {{ location.name }}</ng-template>
      </ul>
  </li>

在组件中,我设置了空assets数组,并设置了空currentLocation

  locations: any[] = [];
  currentLocation: any = {};
  assets: any[] = [];

然后在方法select中,我正在获取这样的资产:

  select(location:any = {){

    if (this.currentLocation != location || !this.assetsVisible) {
      this.assetsVisible = true;
    }
    else {
      this.assetsVisible = false;
    }

    this.currentAddress = address;

    this.locationService.getAssets(location.Id)
      .subscribe(
        assets => this.assets = assets
      );
  }

我想做的是,因为我正在使用the drag and drop plugin for Angular我希望用户可以将资源从一个位置拖到另一个位置。然后暂时将该资产推送到数组assets。 我已经为此做了一个功能:

onItemDrop(e: any, location:any = {}) {
   this.assets = [];
   this.assets.push(e.dragData);        
   this.select(location);
}

因此,当用户将资产从一个位置拖放到另一个位置时,我将清空assets阵列,并推送拖动到阵列的新资产。 但是,在select方法中,我获得了assets被删除location的所有asset,并且重写了assets数组。 如何将那些assets推送到同一个数组,这样我就可以添加新的assetassets我从服务端点获得的location? 我也尝试了另一种方法,我首先清空数组资产,然后调用并将新的location和新的asset传递给select方法:

onItemDrop(e: any, location:any = {}) {
    this.assets = [];
    this.select(location, e.dragData);
  }

然后,在select方法中,我将asset参数设置为可选,然后在我获得所有assets之后将其推送到assets数组来自服务的location

select(location:any = {}, asset?:any = {}) {


    this.locationService.getAssets(location.Id)
      .subscribe(
        assets => this.assets = assets,
        if (asset) {this.assets.push(asset)} 
      );
  }

但是,这不起作用,资产下降到新位置未显示在模板中。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:2)

在您的第一种方法中,您正在覆盖.delete函数中的assets数组:

subscribe

很明显,此时暂时保存在该数组中的this.locationService.getAssets(location.Id).subscribe( assets => this.assets = assets ); 会丢失。

您的第二种方法更有意义,但您在此示例中使用了asset错误:

subscribe

在这种情况下,this.locationService.getAssets(location.Id).subscribe( assets => this.assets = assets, if (asset) {this.assets.push(asset)} ); 部分作为第二个参数传递给if (asset) ...来电subscribe。你想这样做:

error callback

希望它有所帮助。

更新: 我甚至不确定this.locationService.getAssets(location.Id).subscribe( (assets) => { this.assets = assets; if (asset) { this.assets.push(asset) } }); 部分,即你实现它的方式,甚至是作为错误回调。如果调用该回调因为函数是预期的,而不是表达式(但正如我所说,我不确定),你可能会得到一个错误。