使用服务角度递减和递增数组中的数字

问题描述

我有一个问题,我找不到解决方案。如图所示:

This is how my array looks before

This is how my array looks after I clicked at "X" to remove

主要问题是,我无法删除这个数字,每次点击 ID 1 按钮时都会添加 29.99 amountCounter: number;,而没有将我的 amountCounter 减少到与之前相同的值。

假设我按下了 ID 1 按钮一次,我的数组 get 添加了 29.99 因为我的服务中的 getter 被我的函数 initialize() 调用,在那里你可以看到 {{1} } 正在从另一个组件调用号码 29.99。

我的函数 this.amountCounter = this.share.getAmountCounter(); 不起作用,我真的不明白为什么,它确实减少了我的 amountCounter 但我的整个计数器被删除removeElement(id: number,counter: number) 并且它变成了负数。

希望你们能帮助我,我真的很感激!

app.component.html

this.amountCounter -= counter

app.component.ts

<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>

share-data.service.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);
  }
}

感谢您的帮助!

最好的问候

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)