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 expressesion 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
  •    Twitter Bootstrap

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

In the DataService.ts First in the constructor we add our dependency injection the (HttpClient) and then our custom method here we call the WordPress API here you input the URL of your WordPress site


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

@Injectable({
providedIn: 'root'
})
export class DataService {
// Create an Instance - dependency injection
constructor(private http: HttpClient) { }

// Create custom method get the posts from wordpress
getPosts() {
return this.http.get('https://wordpress.com/wp-json/wp/v2/posts');
}
}

This returns JSON in key-value pairs. We will focus on the title: and content: to display in our App

Learn how to make custom endpoints below


[
{
"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":

In the posts.component.ts 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 get and bind the data to our app


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
    );
      console.log(this.data.getPosts()); // check by logging in the console
   }
 }

In posts.component.html we add the ngFor directive to loop through our variable called post of our posts$ observable and render the title and content in our Angular app


<div class="container">

    <h1>Posts</h1>

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

By default the wordpress API will return the last 10 posts of your blog. Thanks for tuning in and I hope this has helped you to add WordPress to your Angular Application. For more information on Angular and the WordPress Api leave me a comment below, your feed back and thoughts are appreciated.

LEARN WORDPRESS API CUSTOM ENDPOINTS

How to use Custom WordPress Restful API

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