首页 > 解决方案 > 数组中的角度递减值

问题描述

我尝试减少数组中的一个值,但我无法让它工作。我的数组data包含属性,每次单击方法时,我都会从服务中调用该值并在数组对象中递增它。吸气剂等于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);
  }
}

共享数据.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();
  }

}

这就是我的数组在点击 ID 1 之前的样子

这就是我单击“X”后我的数组的样子,但它递减错误

非常感谢!

标签: arraysangulartypescriptdecrement

解决方案


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

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

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

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

在这里,您将新项目添加到“数据”数组中,单个项目的值来自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.serviceclickMe()方法中的字段值
  • 该方法将触发一个方法,该方法会将app.componentinitialize项目添加到this.data数组中。
  • 如果您单击项目(将其删除)splice将执行此操作,并且 Angular 将刷新Total调用该getTotalAmount方法

工作Stackblitz


推荐阅读