arrays - 数组中的角度递减值
问题描述
我尝试减少数组中的一个值,但我无法让它工作。我的数组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();
}
}
非常感谢!
解决方案
不确定这是否是您所追求的行为,但通常这种方法会计算数组值的总和
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.component
新initialize
项目添加到this.data
数组中。 - 如果您单击项目(将其删除)
splice
将执行此操作,并且 Angular 将刷新Total
调用该getTotalAmount
方法
工作Stackblitz。
推荐阅读
- vaadin - 如何在 Vaadin 13 中制作侧边菜单?
- java - 尝试使用无头 chromedriver 选项时,Selenium 找不到 WebElements
- ios - 在通过 UIBezierPath 绘制的父视图上添加子视图
- javascript - DataTables:日期范围过滤器触发错误(服务器端处理)
- vba - 我可以通过 VBA 在 Outlook 中创建签名并将其保存为默认签名吗?
- yii2 - 如何在视图中显示多个 GridView,其中一个 DataProvider 按某个字段对其进行分组?
- node.js - 我无法安装 puppeteer 库
- python - Importerror:ubuntu中python2.7.6中没有名为time的模块
- ubuntu - 在构建 VTK 时,ccmake 没有链接到我的 ubuntu 上最新版本的 cmake(ccmake 说 cmake 是 3.5.1 版,我不是!)
- python-3.x - 在一个图中创建 3 个熊猫系列作为饼图