Home > Mobile >  Delete elements before an action
Delete elements before an action

Time:09-15

I have an action to go back, when button is clicked I need to do an api call to delete all items and then go back in another page.

So in my html:

<a  (click)="goBack()" role="button">
                            Back
</a>

goBack(){
  removeItems = this.removeAllItems(this.items)
  if(removeItems) this.router.navigate(["/home"])
  
}

removeAllItems(items){
  items.forEach((item) => {
   let removeItemService = this.itemService.removeItem(item.id)
   removeItemService.pipe(untilDestroyed(this)).subscribe(
     (data) => {console.log("data", data)}
)
    if (products.length === 0) return true
})
}

In my service:

removeAllItems(itemId): Observable<any>{
  let url = .....    itemId
  return this.http.delete(url)
}

Now the problem is that it doesn't enter in
if(removeItems) this.router.navigate(["/home"])

So items are not deleted

CodePudding user response:

Deletion of elements happens asynchronously, while your goBack function seems to be synchronous. I would return an Observable from the removeAllItems function and wait for it to complete before going forward:

removeAllItems(items: any[]): Observable<boolean> {
  return forkJoin(items.map((item) => this.removeItem(item.id))).pipe(
    map((res) => res.length == items.length)
  );
}

removeItem(itemId): Observable<any> {
  let url = /* .....    */ itemId;
  return this.http.delete(url);
}

goBack() {
  this.removeAllItems(this.items)
    .pipe(filter((removedAllItems) => removedAllItems))
    .subscribe(() => this.router.navigate(['/home']));
}
  • Related