Angular 递减数组中的值

Angular decrement value in array

我尝试减少数组中的一个值,但我无法让它工作。 我的数组 data 包含属性,每次单击一个方法时,我都会从服务中调用该值并在数组对象中递增它。 getter 等于 amountCounter.

我的主要问题是,每当我尝试删除数组对象时,我的 amountCounter 不会同时减少它之前的值,但数组对象会被删除。

我也放了两张图来更好的说明我的问题,非常感谢大家的帮助。

app.component.html

<h2>Add values of my service into array:</h2>
<p>Array:</p>
<p>Total: {{amountCounter}}</p>

<div *ngFor="let item of data, let i = index;">
  <span>ID: {{item.id}}</span>
  <span>Title: {{item.title}}</span>
  <span (click)="removeElement(i, item.amountCounter)" class="material-icons">
    close
    </span>
</div>

app.component.ts

export class AppComponent {
  clickEventsubscription: Subscription

  ngOnInit() {
  }

  id: number;
  title: String;
  amountCounter: number;
  data: any = [];

  constructor(private share: ShareDataService) {
    this.clickEventsubscription = this.share.getClickEvent().subscribe(() => {
      this.initialize();
    })
  }

  removeElement(id: number, counter: number) {
    this.data.splice(id, 1);
    this.amountCounter -= counter //In that line I can't get it to work that my attribute decrements
    console.log("before" + this.amountCounter);
    console.log("after:" + counter);
  }

  initialize() {
    this.id = this.share.getId();
    this.title = this.share.getTitle();
    this.amountCounter = this.share.getAmountCounter();

    const newData = {
      id: this.id,
      title: this.title,
      amountCounter: this.amountCounter
    };

    this.data.push(newData);
    console.log(this.data);
  }
}

分享-data.service.ts

export class ShareDataService {
  private subject = new Subject<any>();

  title: String;
  id: number;
  amountCounter: number;

  getId() {
    return this.id;
  }

  getTitle() {
    return this.title;
  }

  getAmountCounter(){
    return this.amountCounter;
  }

  sendClickEvent() {
    this.subject.next();
  }

  getClickEvent(): Observable<any> {
    return this.subject.asObservable();
  }

}

That is how my array looks before ID 1 is clicked

That is how my array looks after I clicked at "X", but it decrements wrong

非常感谢!

不确定这是否是您所追求的行为,但通常此方法会计算数组值的总和

  getTotalAmount(): number {
    return this.data.reduce((acc, item) => acc + item.amount, 0);
  }

我发现很难弄清楚的主要问题是 amountCounter 在 [share-data.service, dialog.component, app.component]

我想您想使用具有不同 amount 值的 dialog.component 添加新项目。

此处您将新项目添加到 'data' 数组,单个项目的值来自 share 服务,该服务已在您的 dialog.component

中更新
  initialize() {
    console.log("initialize");
    const id = this.share.getId();
    const title = this.share.getTitle();
    const amount = this.share.getAmount();

    const newData = {
      id,
      title,
      amount
    };

    this.data.push(newData);
  }

流程总结:

  • dialog.component 中更新字段值 share-data.service clickMe() 方法
  • 该方法将触发 app.component 中名为 initialize 的方法,该方法会将新项目添加到 this.data 数组。
  • 如果您单击项目(将其删除)splice 将执行此操作,并且 Angular 将刷新 Total 调用 getTotalAmount 方法

工作Stackblitz