maf*_*tis 0 javascript ionic-framework angular
我试图在删除和刷新按钮上刷新我的页面,它获取新数据但问题是new data will add to old ones我需要在添加新数据之前清除旧数据。
addresses: any[] = [];
// loads first time data
this.addressService.getAddresses().subscribe((res) => {
for (let address of res['data']) {
this.addresses.push(address);
}
this.hideLoading();
});
// refresh list items
doRefresh(event) {
console.log('Begin async operation');
setTimeout(() => {
console.log('Async operation has ended');
// get new items in list
this.addressService.getAddresses().subscribe((res) => {
for (let address of res['data']) {
this.addresses.push(address);
}
this.hideLoading();
});
event.target.complete();
}, 2000);
}
//remove item and renew list items
removeAddress(id: string){
this.addressService.remove(id).subscribe(
data => {
this.alertService.presentToast(data['message']);
//getting items (renew)
this.addressService.getAddresses().subscribe((res) => {
for (let address of res['data']) {
this.addresses.push(address);
}
this.hideLoading();
});
},
error => {
this.alertService.presentToast(error['message']);
}
);
}
Run Code Online (Sandbox Code Playgroud)
我认为
addresses: any[] = [];在我的doRefresh(event){..}和removeAddress(id: string){...}函数中获取新项目之前我需要清除以避免重复。
任何的想法?
Gen*_*ene 10
假设您的刷新功能有效,
在从 api 获取新项目之前添加此代码
this.addresses =[];
Run Code Online (Sandbox Code Playgroud)
或者
this.addresses.length = 0;
Run Code Online (Sandbox Code Playgroud)
为了实现明智,关于删除功能,您可以从后端删除,清除数组并提取一组新数据,如果您拥有庞大的数据集,这可能会很昂贵。
您可能需要考虑更新后端(删除该特定数据)并从数组中删除该特定索引(当您的删除函数返回成功时)
对于更新,您可以进行比较并更新那些已修改的数组对象。否则,您可以清除数组并重新触发检索 api 函数。