This is an earlier version of a post about consuming a REST service with Angular. A new, fully reworked version for Angular 6+ can be found here. In both versions, I describe how to use angular 4.3+ HttpClientModule. In the new version, I recently have added refactoring stories around service separation and ways of managing subscriptions. We start simple with a working hello world example and work us through by refactoring the code step by step, to reach at a code with a higher maintainability and testability.
I recommend using the new version, but some might find it more convenient to start with the somewhat shorter, old version. Click statistics will show.
In this step-by-step tutorial, we will learn how to consume a REST Service with Angular 5.2. We will perform the following steps:
- install Angular using the Angular CLI
- create an Angular single page application that is consuming a RESTful Web Service with Angular
- make sure that the HTML content is trusted and fully functional.
Updates:
- 2018-05-12
- tested with Angular 6. We are now using pipes similar to the latest Tour of Heros.
- 2018-04-06
- Updated from deprecated HttpModule (@angular/http) to new HttpClientModule (@angular/common/http)
- 2018-03-24
- tested with Angular 5.2
- included information about how to retain the full HTML functionality of the content retrieved via the REST API
Consuming a REST Service with Angular 4.3+ HttpClientModule
At the end of this tutorial, we will have created a simple Angular page that is displaying the contents of a previous blog post on WordPress. The content has been retrieved from the WordPress REST API in JSON format. The title and content will be displayed:
The rest of the article is organized into two phases:
- Installing Angular CLI on CentOS
- Programming the Angular REST Client
Let us start:
Phase 1: Install Angular CLI on CentOS
Step 1.0: Install a Docker Host
This time, we will need to use a real Docker host: i.e., different from our last Angular Hello World Quickstart post, this time it is not possible to use Katacoda as our Docker Host playground. We will install Angular CLI, and this requires more Memory than is provided by Katacoda. If you have no access to a Docker host yet and if you are working on a Windows machine, you might want to follow the instructions found here; search for the term “Install a Docker Host”. It describes step by step how to install a Docker host on Virtualbox using Vagrant. I have made good experiences with that approach. For other operating systems, you may want to consult the official Docker installation instructions.
Note: the official Docker installation instructions for Windows might work as well, but years ago, when I had started with Docker, the official solution had urged me to write a blog post „Why is it so hard to install Docker on Windows“). Those were the times with boot2docker. However, the situation has improved from what I have heard from other colleagues that have started with Docker more recently. Still, I like the Vagrant approach a lot, and I will stick to that solution.
Step 1.1: Start CentOS Container
Let us create a Docker CentOS container on a Docker host:
docker run -it -p 4200:4200 centos bash
We have mapped TCP container port 4200 to the Docker host port 4200 since we want to access the service on this port from outside.
Persistent alternative (optional): to persist the Angular project we will be creating on the Docker host, it makes sense to map a volume from Docker host to Docker container:
mkdir angular-5-on-centos; cd angular-5-on-centos docker run -it -p 4200:4200 -v $(pwd):/localdir centos bash
Step 1.2: Install NodeJS and Angular CLI
On the container:
(container)# yum install epel-release && yum install -y nodejs (container)# npm install -g @angular/cli@1.7.3 (container)# yum install -y git
Note: the second command has been introduced recently, since the latest epel-release is missing the http parser library. See SvennD’s blog for more details.
Note: the git install command has been introduced to allow the creation of a .gitignore file in the next step. The alternative git installation via curl will install a newer version of GIT, which I prefer compared with the old version that comes with the epel-release.
In order to verify the installation, let us check the version of Angular CLI and node:
(container)# ng -v _ _ ____ _ ___ / \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _| / ? \ | '_ \ / _` | | | | |/ _` | '__| | | | | | | / ___ \| | | | (_| | |_| | | (_| | | | |___| |___ | | /_/ \_\_| |_|\__, |\__,_|_|\__,_|_| \____|_____|___| |___/ Angular CLI: 1.7.3 Node: 6.12.3 OS: linux x64 Angular: ...
Step 1.3: Create new Project
Step 1.3.1: Create the Project
Now let us create a project:
cd /localdir ng new my-project-name cd my-project-name
Depending on the speed of your Internet connection, the second command might take some minutes.
We have not installed GIT yet, so we will get following error message at the end:
/bin/sh: git: command not found
Project ‚my-project-name‘ successfully created.
Step 1.3.2 Check the Version of the Project
$ grep @angular/core package.json "@angular/core": "^5.2.0",
We can see that angular has generated a v5.2 Angular project in this case.
Step 1.4: Start the Service
$ ng serve --host 0.0.0.0 ** NG Live Development Server is listening on 0.0.0.0:4200, open your browser on http://localhost:4200/ ** Date: 2018-03-24T14:24:53.729Z Hash: 5aab41746ecad14f6d3b Time: 17472ms chunk {inline} inline.bundle.js (inline) 3.85 kB [entry] [rendered] chunk {main} main.bundle.js (main) 17.9 kB [initial] [rendered] chunk {polyfills} polyfills.bundle.js (polyfills) 549 kB [initial] [rendered] chunk {styles} styles.bundle.js (styles) 41.5 kB [initial] [rendered] chunk {vendor} vendor.bundle.js (vendor) 7.42 MB [initial] [rendered] webpack: Compiled successfully.
Step 1.5: Connect to the Service
If you are running the docker host locally, or if your local port 4200 is mapped to your docker host’s port 4200, we get:
Phase 2: Programming the Angular REST API Client
In this phase, we will see, how easy it is in Angular 2 to 5 to retrieve and display data from a REST API.
Step 2.1: Add HTTP Client Module
First, we need to tell Angular that we will use the HttpClientModule. For that, we edit src/app/app.module.ts (added parts in blue).
Note: since the HttpModule is deprecated now, we have replaced the module by the more modern HttpClientModule.
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ HttpClientModule, BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Step 2.2: Configure Component to use HTTP
In a second step, we configure Edit src/app/app.component.ts:
import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { public title : String = 'Loading title...'; public content : String = ''; constructor(private _http: HttpClient) { } ngOnInit() { this._http.get('https://public-api.wordpress.com/rest/v1.1/sites/vocon-it.com/posts/3078') .subscribe(data => { this.title = data.title; this.content = data.content; console.log(data); }); } }
Step 2.3: Adapt HTML Template
Remove all content of src/app/app.component.html and replace it with the following content:
<h2 style="color:blue;">The following content has been retrieved from the WordPress REST API:</h2> <h1 style="font-size: 250%;" [innerHTML]="title">Loading Title...</h1> <div [innerHTML]="content">Loading Content...</div>
(Sometimes WordPress seemed to have a problem displaying the content correctly, so I post it as a screenshot in addition to the text that might disappear when trying to save the page)
After that, we will see that the browser is displaying following content:
Step 2.4: Fix the Table of Contents
My WordPress page will return a table of contents (TOC) because I have installed TOC plugin. However, you will note that the links to the headlines do not work. We will see the reason in the debug console (press F12) of the Chrome browser:
WARNING: sanitizing HTML stripped some content (see http://g.co/ng/security#xss).
The problem and the workaround is described in my blog post „Angular 4: Automatic Table of Contents – Part 2: Adding Links„.
The problem arises from the fact that Angular does not trust dynamically assigned innerHTML per default. It will remove any IDs found in the content. We can see this easily in the in the elements section of the Chrome browser after entering debug mode (F12):
Angular has removed the ID of the span element. Hence, the links to those IDs will not work.
To fix this problem, we have to tell Angular explicitly, that it should trust the innerHTML content. This is done in the component as follows (changes in blue):
import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { DomSanitizer, SafeHtml } from '@angular/platform-browser'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { public title : SafeHtml|String = 'Loading title...'; public content : SafeHtml|String = 'Loading content...'; constructor(private _http: HttpClient, private _sanitizer: DomSanitizer) { } ngOnInit() { this._http.get('https://public-api.wordpress.com/rest/v1.1/sites/vocon-it.com/posts/3078') .subscribe(data => { this.title = this._sanitizer.bypassSecurityTrustHtml(data.title); this.content = this._sanitizer.bypassSecurityTrustHtml(data.content); console.log(data); }); } }
We check again the element in the debug mode of the chrome browser (F12): the IDs are present now:
With that, the links work as expected: When clicking the table of contents link, the browser will jump to the corresponding headline:
Summary
In this hello world style step-by-step guide, we have learned how to
- install an Angular 5 project using the Angular CLI and
- consume the WordPress API for retrieving and displaying a blog post title and HTML content.
- tell Angular to trust the „innerHTML“ content retrieved from the API
Next steps
- Retrieve a list of Blog Posts instead of a single post only.
- Figure out to handle the fact that retrieving all posts takes a lot of time initially; the WordPress REST API does not seem to allow to retrieve the list of titles only. Do we need to create an improved REST service that is quicker and allows to
- The REST client can be separated in its own service like shown in this article.
Appendix: Exploring the WordPress REST API
The WordPress API can be explored via the WordPress.com REST API console.
You need to login via and your WordPress.com credentials.
There seem to be several types and versions of APIs:
- WP.COM API
- v1.1 (default)
- v1
- WP REST API
- wp/v2
- wpcom/v2
In this Proof of Concept / Hello World, we are using the WP.COM API V1.1 to retrieve the content of a single WordPress blog post of mine:
https://public-api.wordpress.com/rest/v1.1/sites/vocon-it.com/posts/3078
However, we can also use the WP REST API wp/v2:
https://public-api.wordpress.com/wp/v2/sites/vocon-it.com/posts/3078
Because of the organization of the wp/v2 result, we need to exchange data.title
by data.title.rendered
and data.content
by data.content.rendered
in the HTML template, though.
Note: wp/v2 API does not seem to work with our new primary domain vocon-it.com. We have changed the primary stite from vocon-it.com to vocon-it.com a week ago.
References:
- See this blog post for a more elaborate Angular 4 REST example promoting end-to-end tests.
- Consuming a REST API with Angular Http-Service in Typescript
- WordPress.com REST API console
- AngularJS REST hello world by Spring (Angular 1)
- An article showing how to separate the REST client into its own service: Getting Started With Angular 2 Step by Step: 6 – Consuming Real Data With Http
Your article helped me a lot, is there any more related content? Thanks!