微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决使用服务角度递减和递增数组中的数字

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

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 举报,一经查实,本站将立刻删除。