Search code examples
angularmultidimensional-arrayangular2-routingangular2-servicesangular2-http

Angular 2 - How to delete or update nested objects - Tour of Heroes


I decided to complicated tutorial of Angular2 "Tour of heroes" by creating several towers. https://angular.io/docs/ts/latest/tutorial/

We created the database with Angular in-memory-web-api : https://github.com/angular/in-memory-web-api

Here is the tutorial database (just an array of heroes) :

heroes: [
      {id: 11, name: 'Mr. Nice'},
      {id: 12, name: 'Narcos'},
      {id: 13, name: 'Bombasto'},
      {id: 15, name: 'Magneta'}
    ]

and this is mine (an array of towers which contains an array of heroes):

towers = [
  {id: 1, title: 'Tower 1', heroes: [
      {id: 12, name: 'Narcos'},
      {id: 13, name: 'Bombasto'}
    ]
  },
  {id: 2, title: 'Tower 2', heroes: [
      {id: 14, name: 'Celeritas'},
      {id: 15, name: 'Magneta'},
    ]
  },
  {id: 3, title: 'Tower 3', heroes: [
      {id: 16, name: 'RubberMan'},
      {id: 17, name: 'Dynama'}
    ]
  }
]

In my service file i created this function to delete a tower and it works:

deleteTower(idTower: number): Promise<void> {
    const url = `${this.towersUrl}/${idTower}`;
    return this.http.delete(url, {headers: this.headers})
        .toPromise()
        .then(() => null)
        .catch(this.handleError);
}

The problem is when i want to delete a specific hero in a specific tower ('/towers/1/heroes/12')

deleteHero(idTower: number, idHero: number): Promise<void> {
    const url = `${this.towersUrl}/${idTower}/heroes/${idHero}`;
    return this.http.delete(url, {headers: this.headers})
        .toPromise()
        .then(() => null)
        .catch(this.handleError);
}

This function delete the tower and not just a hero.

So i don't know how to delete or update directly a hero ?

Thank you


Solution

  • I finally used the subdocuments because with mongodb there isn't foreign keys.