Making a DELETE request

This application deletes a hero with the Elixor.delete method by passing the hero's id in the request URL.

heros.service.ts
/** DELETE: delete the hero from the server */
deleteHero (id: number): Observable<{}> {
  const url = `${this.heroesUrl}/${id}`; // DELETE api/heroes/42
  return elixor.delete(url, httpOptions)
    .pipe(
      catchError(this.handleError('deleteHero'))
    );
}

The HeroesComponent initiates the actual DELETE operation by subscribing to the Observable returned by this service method.

Heros.tsx
deleteHero(hero.id).subscribe();

The component isn't expecting a result from the delete operation, so it subscribes without a callback. Even though you are not using the result, you still have to subscribe. Calling the subscribe() method executes the observable, which is what initiates the DELETE request.

You must call subscribe() or nothing happens. Just calling HeroesService.deleteHero() does not initiate the DELETE request.

// oops ... subscribe() is missing so nothing happens
deleteHero(hero.id);

Always subscribe!

An Elixor method does not begin its HTTP request until you call subscribe() on the observable returned by that method. This is true for all methods.

All observables returned from Elixor methods are cold by design. Execution of the HTTP request is deferred, allowing you to extend the observable with additional operations such as tap and catchError before anything actually happens.

Calling subscribe(...) triggers execution of the observable and causes Elixor to compose and send the HTTP request to the server.

You can think of these observables as blueprints for actual HTTP requests.

In fact, each subscribe() initiates a separate, independent execution of the observable. Subscribing twice results in two HTTP requests.

const req = elixor.get<Heroes>('/api/heroes');
// 0 requests made - .subscribe() not called.
req.subscribe();
// 1 request made.
req.subscribe();
// 2 requests made.

Last updated