Hello, welcome to therichpost.com. In this post, I will tell you How to Get WordPress data in Angular2 with WordPress rest api/ Nowadays Angularjs is very popular and known as one page website. I am familiar with Angular 1 very well but Angular 2 is totally different with Angular 1. Angular2 is totally command based. WordPress is the best cms. WordPress hooks(add_action, add_filter) give us the power to edit or change the code without interruption into the files and this is the best thing about wordpress.
We will get WordPress data in json format and get in angular2 with http services and show in Angular2 template with ng directives.
Image of WordPress data in json format After Rest Api Hook:
Like In my last post, I told you How to get all users in wordpress with rest api hook?
Finally here is the working WordPress Rest Api and you need to add this code into your theme’s functions.php file:
add_action( ‘rest_api_init’, function () {
register_rest_route( ‘wp/v2’, ‘/getusers/’, array(
‘methods’ => ‘GET’,
‘callback’ => ‘get_users_names’
) );
} );function get_users_names()
{
global $wpdb;
$myArr = array();
$wp_user_search = $wpdb->get_results(“SELECT ID, display_name FROM $wpdb->users ORDER BY ID”);foreach ( $wp_user_search as $userid ) {
$myArr[] = stripslashes($userid->display_name);
}
$myJSON = json_encode($myArr);
echo $myJSON;
die();
}
Here please check code in angularjs 2 component and you need to add the code in component(app.component.ts):
import { Component, OnInit } from ‘@angular/core’;
import { Http, Response ,RequestOptions,Headers} from ‘@angular/http’;
@Component({
selector: ‘app’,
templateUrl: ‘./app.component.html’,
styleUrls: [‘./app.component.css’]
})
export class AppComponent implements OnInit {
posts: any;
constructor(public http: Http) {this.http.get(‘http://localhost/wordpress49/wp-json/wp/v2/getusers/’).map(res => res.json()).subscribe(data => {
this.posts = data;
console.log(this.posts);
});
}
ngOnInit() {
}}
Here please check code in angularjs 2 Html component and you need to add the code in html component(app.component.html):
<table class=”table table-hover”>
<thead>
<tr>
<th>#</th>
<th>Wordpress Users Name</th>
</tr>
</thead>
<tbody>
<tr *ngFor=”let name of posts”><td>#</td>
<td>{{ name}}</td>
</tr></tbody>
</table>
There are many more code in Angular2 and WordPress and i will let you know all. Please do comment if you any query related to this post. Thank you. Therichpost.com
Recent Comments