Consuming WordPress Rest API with Angular
In this article, we will be looking at how to consume WordPress Rest Api With Angular.
For the purpose of this tutorial we will be using MaterialPro Angular 8 Lite Template.
Below is what we need to know before we proceed:
- Node.js installed in our system
- Angular CLI installed in our system
- A text editor
- Little knowledge of the framework(Angular)
- How to call API
Prerequisite
MaterialPro Angular 8 Lite is a free Material dashboard template built on the Angular framework. Its modular design allows it to be easily customized and it comes with a host of reusable beautiful UI elements. The MaterialPro Angular admin template is responsive by design and works well with all mobile, desktop, and laptop screen sizes.
It uses the essential Angular components along with preset design patterns and re-styling plugins to craft consistent web designs and enhanced user interfaces.
Download the the template and run the below command.
npm install
The command above creates a node_module folder and adds dependencies from package.json file to its module folder.
What is WordPress API
The WordPress REST API provides an interface for applications to interact with your WordPress site by sending and receiving data as JSON (JavaScript Object Notation) objects. It is the foundation of the WordPress Block Editor, and can likewise enable your theme, plugin or custom application to present new, powerful interfaces for managing and publishing your site content.
How to use WordPress API
The WordPress API uses HTTP verbs appropriate to each action.
Verb | Description |
GET | should be used for retrieving data from the API. |
POST | should be used for creating new resources (i.e users, posts, taxonomies). |
PUT | should be used for updating resources. |
DELETE | should be used for deleting resources. |
The API is available at https://epower.ng/wp-json/wp/v2/posts. Responses are sent as JSON.
The API has a lot of parameters that we can use, but we’ll only need 2 of them which are :
- Page: specify the page of results to return.
- Per_page: specify the number of records to return in one request, specified as an integer from 1 to 100.
Setting up the server
We are going to generate Angular Service and import HttpClientModule in our project so that we can be able to interact with the WordPress API through http.
Run the code below to generate angular service:
ng generate service api
Open app.module.ts and import HttpClientModule and Service
import { HttpClientModule } from "@angular/common/http";
import { ApiService } from './api.service';
@NgModule({
declarations: [...],
imports: [
HttpClientModule
],
providers: [ApiService],
bootstrap: [...]
})
export class AppModule { }
Open app.api.service.ts and write the code below but first we have to import HttpClientModule.
import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
@Injectable({
providedIn: "root"
})
export class ApiService {
constructor(private httpClient: HttpClient) {}
Now write the code below:
base_path = `https://epower.ng/wp-json/wp/v2/posts?page=1&per_page=6`;
getBlog() {
return this.http.get(this.base_path).pipe(retry(2), catchError(this.handleError));
}
handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(`Backend returned code ${error.status}, ` + `body was: ${error.error}`);
}
// return an observable with a user-facing error message
return throwError('Something bad happened; please try again later.');
}
We create a global variable that we hold our API, a getBlog() function to fetch blog from WordPress Api and an error handler.
Fetching data
Now, we are going to fetch data from the WordPress Api. Open dashboard.component.ts. We will start by import Service so we can be able to access the api end point.
import { Component, OnInit } from '@angular/core';
import { ApiService } from "../api.service";
@Component({
selector: 'app-view',
templateUrl: './view.component.html',
styleUrls: ['./view.component.scss']
})
export class ViewComponent implements OnInit {
constructor(private apiService: ApiService) { }
ngOnInit() {
}
}
We are going to make a call to our Api service.
ngOnInit() {
this.getAllBlog();
}
getAllBlog() {
this.loading = true;
this.apiService.getBlog().subscribe(response => {
console.log(response);
this.loading = false;
this.blogData = response;
});
}
In the ngOnInit, we called a function which holds the logic that makes an call the server.
we subscribe to the WordPress Api by calling the this.apiService and the getBlog() function we created in the ApiService and we console.log the response we get from the serve and we assign the value to a global variable so we can access the responses and display them.
We are going to serve our app and see the response we are getting:
ng serve -o
If our app is serve successfully, open the dev tools and if the response are in array of 6 items as shown below, then you are on the right track but if not, then you might be missing out somewhere.
Array(6) [ {…}, {…}, {…}, {…}, {…}, {…}, … ]
Displaying Image
Now that we have gotten a success response we will move further to display our response than going to the console and we will be using angular `*ngFor` and We used the Material syntax to build UI. Check out the Documentation if you are haven’t used it before.
Open dashboard.component.html and delete the file and replace it with this.
<div fxFlex.gt-lg="99" fxFlex.gt-md="99" fxFlex.gt-xs="100" fxFlex="100">
<mat-card>
<mat-tab-group>
<mat-tab label="Activity">
<mat-card-content>
<div
class="d-flex no-blcok"
*ngFor="let blog of blogData"
id="showFristBlog"
>
<div class="p-b-20 b-b m-b-30">
<div fxLayout="row wrap">
<div fxFlex.gt-md="40" class="mb-4" fxFlex="100">
<img
class="img-responsive rounded"
width="400"
src="{{ blog.featured_image }}"
alt=""
/>
</div>
</div>
<a
[routerLink]="['/single-view', combineSlug(blog.slug, blog.id)]"
>
<div class="display-card">
<h4 color="headingtext">{{ blog.title.rendered }}</h4>
<p [innerHTML]="blog.excerpt.rendered"></p>
</div>
</a>
</div>
</div>
<div class="row mb-3 mt-3">
<div class="col-6">
<button (click)="previous()">Previous</button>
</div>
<div class="col-6">
<button (click)="next()">Next</button>
</div>
</div>
</mat-card-content>
</mat-tab>
</mat-tab-group>
</mat-card>
</div>
If we look at our web browser again we blog been displayed but it dose not look fine and a little styling can help. Open dashboard.component.scss
.position-relative {
position: relative;
}
.add-contact {
position: absolute;
right: 17px;
top: 57px;
}
.row .col-6 {
text-align: center;
}
.row .col-6 button {
border-radius: 20px;
border: none;
background-color: #e6294b;
padding: 10px 40px;
color: #fff;
}
.row .col-6 button:hover {
border: 1px solid #e6294b;
color: #e6294b;
background-color: #fff;
}
Now it look much better.
Add Pagination to Blog
We are going to our next and previous page active.
page = 1;
next() {
this.apiService.nextUser(this.page += 1).subscribe(data => {
console.log(data);
if (data) {
this.blogData = data;
}
});
}
previous() {
if (this.page > 1) {
this.apiService.previousUser(this.page -= 1).subscribe(data => {
console.log(data);
if (data) {
this.blogData = data;
}
});
}
}
}
We created a function next(), previous() and also we declare global variable which holds the page counts.
The next() function update the page counts and the previous() reduce the page counts by going back to page before the current view page.
We passed the page count in the both function as a parameter.
Open the app.api.service.ts
nextUser(page) {
return this.http
.get(`https://epower.ng/wp-json/wp/v2/posts?page=${(page)}&per_page=6`)
.pipe(retry(2), catchError(this.handleError));
}
previousUser(page) {
return this.http
.get(`https://epower.ng/wp-json/wp/v2/posts?page=${(page)}&per_page=6`)
.pipe(retry(2), catchError(this.handleError));
}
We passed the page count in both functions and also in the API end points.
We can serve our app now to see if the next and previous buttons are working.
Yea it works and it looks really great.
Conclusion
We have finally completed our app and it was cool right?. We were able to learn how to use WordPress API and how to implement pagination and most.
Thanks for reading. If you’ve enjoyed this article you can get the Github Repo and please leave a star.