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

数组中的角度递减值

如何解决数组中的角度递减值

我尝试减少数组中的一个值,但我无法让它工作。 我的数组 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);
  }
}

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

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

我想您想使用具有不同 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.service clickMe() 方法中的字段值
  • 该方法将触发 app.component 中名为 initialize 的方法,该方法会将新项目添加到 this.data 数组中。
  • 如果您点击项目(删除它)splice 会这样做,Angular 将刷新 Total 调用 getTotalAmount 方法

工作Stackblitz

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。