Migrating from Angular HttpModule to new Angular 4.3 HttpClientModule

TL;DR One of the prominent things in the Angular 4.3 announcement is the introduction of HttpClient ("...a smaller, easier to use, and more powerful library for making HTTP Requests.").

Note: This post wraps up the necessary changes done to the small Spring Boot/Gradle based sample spring-boot-kisses-angular used in our previous post Spring Boot kisses Angular 4.

Basically we followed the steps described in Angular - How to use HttpClientModule? to get started:

  • Remove the @angular/http package from your package.json
  • Replace HttpModule with HttpClientModule:
import { HttpModule } from '@angular/http';

becomes

import { HttpClientModule } from '@angular/common/http';
  • Replace Http with HttpClient:
import {Http} from '@angular/http';

becomes

import { HttpClient } from '@angular/common/http';
  • Remove manual extraction of JSON:
return this.http
    .get('../server/version')
    .map(response => <AppVersion> response.json());

becomes

return this.http.get('../server/version');

Looks way better. I like it!

Right after the smooth migration of this Hello World like app I tackled our Online Spring Boot Banner Generator.

The only noteworthy request (non JSON but plain text) with parameters and headers resulted in a clean get request, also:

render(text: string, font: string): Observable<string> {
  const params = new HttpParams()
    .set('text', text)
    .set('font', font);
  const headers = new HttpHeaders().set('Accept', 'text/plain');

  return this.http.get('/renderBannerTxt', {responseType: 'text', headers, params});
}

No post-processing of the result with .map((res: Response) => res.text()); and no RequestOptions anymore.