Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
149
rated 0 times [  152] [ 3]  / answers: 1 / hits: 35437  / 5 Years ago, wed, september 11, 2019, 12:00:00

I am trying to refresh my page on delete and refresh button, it gets new data but the issue is new data will add to old ones I need to clear old data before adding new data.



Code



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']);
}
);
}



I think that I need to clear addresses: any[] = []; before getting
new items in my doRefresh(event){..} and removeAddress(id:
string){...}
functions to avoid duplicates.




Any idea?


More From » angular

 Answers
12

Assuming your refresh function works,



add this code before you get new items from your api



this.addresses =[];


or



this.addresses.length = 0;


For implementation wise, in regards to delete function, you can delete from your backend , clear your array and pull a fresh set of data which might be costly if you have a huge dataset.



You might want to consider updating your backend (delete that specific data) and removing that specific index from your array (when your delete function returns success)



For update, you can do a comparison and update those those array objects that has been modified. Else you can just clear your array and retrigger your retrieve api function.


[#51668] Wednesday, September 4, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ronaldo

Total Points: 694
Total Questions: 85
Total Answers: 103

Location: Somalia
Member since Mon, Feb 27, 2023
1 Year ago
;