Learn Angular 6 and the WordPress API, Headless CMS

Benefits of Angular Javascript Framework

The beauty of Angular and its main advantages of its framework is that a lot of the work is done for you, under the hood so to speak.

To understand the benefits of the Angular framework I’ll start with the MVC (model view controller), I’ll try and simplifier it the best I can. The MVC is a very useful and popular design pattern and can be one of the hardest to truly understand.

So let’s best understand this by building an example app, I’ll call this My-Blog-App and for this project I’ll be using the WordPress REST API as the backend and Angular to view the app on the frontend. In simple terms all the data will come from the WordPress REST API as a JSON object and then we will using the Angular CLI (version 6.0.8) and some front-end development skills to build the app. Let’s take a look…

Quick Overview of MVC

The model represents the data, and does nothing else. The view displays the data. The controller interprets user actions such as button clicks.

The Model

The JSON object is all the data of our application, which is known as the model and this is what we will be using to display on the screen and we’ll be using HTML to generate this model.

Note: The model does NOT depend on the controller or the view.

The View

We will start the view with a HTML unordered list for this example and some Angular directives.

The ngFor directive will loop through the list of blog post we have in WordPress.
The data binding {{ .. …. }} expression will output the data to the view

These expressions are how Angular uses the data and the view to tie it all together

The Controller

The controller provides the model data to the view, and interprets user actions such as button clicks. The controller depends on the view and the model. In some cases, the controller and the view are the same object.

Connecting Angular 6 and WordPress API

In this tutorial, you’ll learn how to build an Angular Blog App. We’ll connect Angular to the WordPress API to retrieving the data to view into the front-end framework of Angular.

The Outcome:

  •    Using Angular 6 front-end framework.
  •    Work with WordPress as the back-end.
  •    Creating Single Page App Blog.
  •    Requests/Endpoints.
  •    Listing posts..
  •    Styling (looks pretty).

Prior Knowledge

  •    Use of Angular & WordPress
  •    Basic JavaScript/Typescript
  •    HTML & CSS
 

Starting Angular 6 Project

We use the Angular CLI to start the new project called My-Blog-App and we add routing

ng new My-Blog-App --routing

NEXT we cd into My-Blog-App and run:

 
ng serve

Now we create 2 component called home and posts

ng g c home
ng g c posts

we also need to import the HttpClientModule from @angular/core


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';
import { HomeComponent } from './components/pages/home/home.component';
import { PostsComponent } from './components/https/posts/posts.component';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    PostsComponent,
],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

NEXT we create a service called data

ng g s data

First in the constructor we add our dependency injection the (HttpClient) and then our custom method called getPosts. Here in the method we call the WordPress API add the URL of your WordPress site.

dataService.ts

import { HttpClient } from '@angular/common/http'; 
import { Injectable } from '@angular/core'; 



@Injectable({ providedIn: 'root' }) 

// Create an Instance - dependency injection
export class DataService{  constructor(private http: HttpClient) { }
 
// Create custom method get the posts from WordPress 
getPosts() { 
return this.http.get('https://ewebdesigns.com.au/wp-json/wp/v2/posts'); 
  } 
}

This returns JSON an array of objects in key value pairs. We will focus on the title: date: and content: to display in our App


[
{
"id": 1070,
"date": "2018-06-25T00:24:15",
"date_gmt": "2018-06-25T00:24:15",
"guid": {
"rendered": "https://ewebdesigns.com.au/?p=1070"
},
"modified": "2018-06-25T00:26:18",
"modified_gmt": "2018-06-25T00:26:18",
"slug": "benefits-of-angular",
"status": "publish",
"type": "post",
"link": "https://ewebdesigns.com.au/benefits-of-angular/",
"title": {
"rendered": "Benefits of Angular"
},
"content": {
"rendered":

Learn how to make custom endpoints below

NEXT retrieving the data we first Pass in the DataService in the constructor, next we ‘ll add a property for holding the return data from the API and last we will subscribe to get and bind the data to our app and console log the result.

posts.component.ts

import { DataService } from './../../../data.service';
import { Component, OnInit } from '@angular/core';

@Component({
selector: 'app-posts',
templateUrl: './posts.component.html',
styleUrls: ['./posts.component.scss']
})
export class PostsComponent implements OnInit {
// Add a property for holding the return data from API
posts$: Object;

// Passing in the data service
constructor (private data: DataService) { }

// Getting and binding the data
ngOnInit() {
this.data.getPosts().subscribe(
data => this.posts$ = data
);
// check by logging in the console
console.log(this.data.getPosts());
 }
}

NEXT displaying the post on the front-end

we add the ngFor directive to loop through our variable called post of our posts$ observable and render the title, content and post date in our Angular app

posts.component.html

<h1>Angular 5 & WordPress API</h1>

<ul>

    <li *ngFor="let post of posts$">
        <h2>
            <div [innerHTML]="post.title.rendered"></div>
        </h2>
      <br>

        </div>
        <div [innerHTML]="post.content.rendered"></div>

        <p>{{post.date}}</p>

    </li>

</ul>

WordPress by default will return the last 10 posts from your website.

Thanks, hope this helps you integrate your Angular app with the WordPress API.

How to use Custom WordPress Restful API Endpoints

A much more cleaner way to return JSON data from WordPress

2 Comments

  1. Neeraj on September 20, 2018 at 3:29 pm

    Alvic,

    What is this exactly … after following everything you detailed here I end up nowhere but the default page of sample angular app. It was not expected. I know you explained how to use wordpress api in any Angular app but forgot to mention how to make use of this in actual.

    This is incomplete in itself … complete it. Thanks.

    • alvic on September 21, 2018 at 2:38 am

      following along returns the API call?, you need to add your WordPress URL in the data service getPosts() method.
      This is a complete call to the WordPress API that returns JSON that you then covert through the HTML component.
      After your URL call check your console and see if its returning the JSON? or what errors are you getting?

Leave a Comment