Consuming a RESTful Web Service with Angular 4


In this step by step hello world style tutorial, you will learn how to

  • install Angular 4 using the Angular CLI
  • create an Angular single page application that is consuming and displaying data from a REST API (the WordPress API in this case)

At the end, we will have created a simple Angular 4 page that is displaying the contents of my previous blog post on WordPress, a post about Angular 4 Quickstart installation. The content has been retrieved from the WordPress REST API in JSON format. The title and content will be displayed:

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.

Step 1.1: Start CentOS Container

Let us create a Docker CentOS container. In the simplest case, this is done on a Docker host via:

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. I am using Vagrant with a synced folder on /vagrant (from point of view of the VirtualBox VM), so I have created a folder on this place for this purpose:

mkdir /vagrant/angular-4-on-centos; cd /vagrant/angular-4-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 -y epel-release
(container)# yum install -y nodejs
(container)# npm install -g @angular/cli

In order to verify the installation, let us check the version of Angular CLI and node:

(container)# ng -v
    _                      _                 ____ _     ___
   / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
  / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
 / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
/_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
               |___/
@angular/cli: 1.1.0
node: 6.10.3
os: linux x64

Step 1.3: Create new Project

Now let us create a project:

cd /localdir
ng new my-project-name
cd my-project-name

Step 1.4: Start Service

ng serve --host 0.0.0.0

> my-project-name@0.0.0 start /localdir/my-project-name
> ng serve

** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200 **
Hash: 46f1654c27ac4755fbcd
Time: 9010ms
chunk    {0} polyfills.bundle.js, polyfills.bundle.js.map (polyfills) 158 kB {4} [initial] [rendered]
chunk    {1} main.bundle.js, main.bundle.js.map (main) 5.29 kB {3} [initial] [rendered]
chunk    {2} styles.bundle.js, styles.bundle.js.map (styles) 10.5 kB {4} [initial] [rendered]
chunk    {3} vendor.bundle.js, vendor.bundle.js.map (vendor) 2.11 MB [initial] [rendered]
chunk    {4} inline.bundle.js, inline.bundle.js.map (inline) 0 bytes [entry] [rendered]
webpack: Compiled successfully.

Step 1.5: Connect to Service

If port 4200 is mapped to Vagrant port 4200 we get:

Excellent! Thump up!

Phase 2: Configure REST API Client

In this phase, we will see, how easy it is in Angular 2 or 4 to retrieve and display data from a REST API.

Step 2.1: Add HTTP Module

First we need to tell Angular that we will use the HttpModule. For that, we edit src/app/app.module.ts (added parts in red)

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule }    from '@angular/http';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    HttpModule,
    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 } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import 'rxjs/add/operator/map'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  data: any = null;

  constructor(private _http: Http) {
    this.getMyBlog();
  }

  private getMyBlog() {
    return this._http.get('https://public-api.wordpress.com/rest/v1.1/sites/oliverveits.wordpress.com/posts/3078')
                .map((res: Response) => res.json())
                 .subscribe(data => {
                        this.data = data;
                        console.log(this.data);
                });
  }

}

Step 2.3: Adapt HTML Template

Remove all content of src/app/app.component.html and replace it by the following content:

(WordPress seems to have a problem displaying the content correctly, so I had to post it as a screenshot this time)

After that, we will see that the browser is displaying following content:

With that, we have created a little proof of concept how to retrieve data from a REST API and display the data dynamically.

Excellent! Thump up!

Summary

In this hello world style step-by-step guide, we have learned

  • how to install Angular 4 using the Angular CLI and
  • how to consume the WordPress API for retrieving and displaying a blog post title and HTML content.

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.
  • Optionally, this.getMyBlog function can be placed in an ngOnInit function instead of calling it in the constructor. It is not clear to me yet, what are the advantaged/disadvantages of this method.

Appendix: Exploring the WordPress REST API

The WordPress API can be explored via the WordPress.com REST API console.

You need to login via Sign in - WordPress Developer Console 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/oliverveits.wordpress.com/posts/3078

However, we can also use the WP REST API wp/v2:

https://public-api.wordpress.com/wp/v2/sites/oliverveits.wordpress.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.

References:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s