In this tutorial, we see how to list the WordPress posts in an angular application. I’ll use bootstrap for styling the angular application easily and responsive.WordPress posts can’t able to show all posts in the angular app, it increases the dom size, it takes rendering time more. In this example I showed as a 10 latest posts per page, the next upcoming posts are shown as page navigation.
Now we will dive into the concept, there are steps and video tutorials provided in this blog
Steps
- Install the Bootstrap in the angular app, install the latest version of bootstrap using the npm command, it installs the latest version of bootstrap.
npm install bootstrap
- Next, add the boostrap.min.css in angular JSON under styles array, then rerun the angular app, the bootstrap styling will work.
"styles": [
"src/styles.scss",
"node_modules/bootstrap/dist/css/bootstrap.min.css"
],
- Then create the components for post element, pagination, navbar using the following command
ng g c componentname
- Next, a create service for HTTP requests for getting WordPress posts.
- GetPost method is used for getting HTTP request using HTTP Client Module
- Then Get post returns an observable, so you can subscribe.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class PostsService {
constructor(private http: HttpClient) { }
configUrl = 'http://localhost/angularUniversal/backendUniversal/wordpress/wp-json/wp/v2/posts';
getPosts(){
return this.http.get(this.configUrl);
}
}
- Then console here, and also check the network the tabs, it shows the response
- In the component, I write a getPostsWordpress method to get the request.
getPostsWordpress(){
this.posts.getPosts().subscribe((res)=>{
console.log(res)
})
}
- In the next step, I used on ngOnInit angular hook for getting post when the component load on application, it returns nothing so I used void here.
ngOnInit(): void {
this.getPostsWordpress();
}
These steps are explained clearly in the video below and provide the code in the Github repository link.
Youtube Tutorial Video Link Github Frontend Repo Link Github Backend Repo LinkThe next steps are coming soon, stay tuned on maxicsolutions.