Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular clear array

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?

like image 205
mafortis Avatar asked Jun 06 '26 11:06

mafortis


1 Answers

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.

like image 65
Gene Avatar answered Jun 08 '26 23:06

Gene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!