订阅服务作为* ngFor数组的长度

时间:2019-04-01 10:54:50

标签: javascript html angular angular-material

我有一个具有ngFor的div和一个在div内的按钮,它调用了一个弹出式弹出事件

<div *ngFor="let order of orders">
  <button mat-icon-button [satPopoverAnchorFor]="popover_address" (click)="openAddressView(order)">
   <mat-icon matTooltip="Edit Address" class="icon">edit_location</mat-icon>
  </button> 
</div>

<sat-popover (closed)="closeAddressView()" #popover_address horizontalAlign="end" hasBackdrop verticalAlign="center">
    <app-order-address></app-order-address>
</sat-popover>

在调用服务的组件中

openAddressView(order: any){
    this.popover_address.open();
    this.ordersService.getAdddresses(order);
}

并按以下方式订购服务。

import { Component, OnInit, OnDestroy, Input, ChangeDetectorRef, 
ViewChild } from '@angular/core';
import { AgmMap, AgmMarker, AgmCoreModule } from '@agm/core';
import { MapsAPILoader } from '@agm/core';
import { OrdersService } from '../../../Services/orders- 
service/orders.service';
import { SatPopover } from '@ncstate/sat-popover';

@Component({
  selector: 'app-order-address',
  templateUrl: './order-address.component.html',
  styleUrls: ['./order-address.component.scss']
})
export class OrderAddressComponent implements OnDestroy {
  title: string = 'address';
  lat: number = 33.8950888;
  lng: number = 35.5186542;
  zoom: number = 8;
  height: string = '500px';
  addresses: Array<any>;
  selectedAddressId: number;
  @ViewChild(AgmMap) private myMap: any;
  @ViewChild('mapContainer') mapContainer: any;
  @ViewChild(AgmMarker) AddressPin: any;

 constructor(private OrdersService: OrdersService, private cdr: 
ChangeDetectorRef) {

  this.OrdersService.loadClientAddresses.subscribe((response: any) => {
    this.addresses = response.addresses;
    this.selectedAddressId = response.selected_address.id;
    this.recenterMap(response.selected_address.lat, 
    response.selected_address.lon);
    console.log(response); // PRINTS 10 TIMES
    this.cdr.detectChanges();
  });

}

除单击按钮打开弹出窗口外,其他所有选项均正常运行。 console.log打印为订单对象的长度。例如(如果我有10个订单,它将打印10次)

我希望它仅在单击时订阅该服务。

1 个答案:

答案 0 :(得分:0)

可能是因为您有10个app-order-address实例。即使没有触发弹出窗口,该组件也会为每个弹出窗口构造一个应用程序订单地址(?)...(使用“ constructor”方法顶部的“ console.log”进行测试)

如果有10个构造函数调用,则有10次订阅。因此,当您单击一个按钮时,它将触发所有10个订阅。

您应该在父组件中移动一些逻辑(也许还会在rxjs中寻找“ sharedReplay”)