Connecting Angular and the WordPress API with wp-api-angular

Original Source: https://www.sitepoint.com/angular-wordpress-wp-api-angular/

In this tutorial, you’ll learn how to work with the wp-api-angular library that allows you to interact with the WordPress API from Angular 2+ applications. This library supports all major WP resources including users, posts, comments, media, taxonomies etc. It’s also quite simple to use, so you’ll get the idea in no time.

To see the library in action, we’re going to code the following features:

Authentication using JWT
Listing the users
Listing the posts
Creating and editing the posts
Deleting the posts

By the end of the article, you’ll become familiar with this library and will be ready to use it on your own.

The source code for this tutorial is available on GitHub.

I’ll assume you’re using Angular 5, but all explained concepts should be valid for Angular 2 as well.

Laying Foundations
Setting Up WordPress

Before we proceed to writing the code, there are a couple of things to take care of. First of all, note that the API we’re going to utilize works only with the self-hosted version of WordPress. For the web version (which can be configured via the WordPress site), there’s a separate API that has many similar concepts, though it’s still quite different.

You also have to enable permalinks — which is required for the API client to work correctly. For Nginx, you’ll need to add the following line to the nginx.conf file:

try_files $uri $uri/ /index.php?$args;

More detailed information and explanations on how to enable permalinks can be found in this WordPress Codex guide.

Lastly, we should take care of WordPress security which, as they say, is above all. For that, a special plugin called JWT Authentication is required. We’re going to use it in order to authenticate our API client with the help of special tokens (an approach that’s quite common these days).

That’s pretty much it. If you’d like to learn more about the WordPress API in general, skim through this article. When you’re ready, proceed to the next step and let’s see the Angular WordPress client in action!

Bootstrapping an Angular Application

Now that we have WordPress prepared, create a new Angular application by running:

ng new wp-api

This is going to create a skeleton for the application. We’re not going to discuss its structure thoroughly, but you may find more information in our Angular series.

Next, cd into the directory and install the library itself:

cd wp-api
npm install -g typings
npm install wp-api-angular –save

Now we need to import the proper components inside the src/app/app.module.ts file:

// … other imports
import { Http } from ‘@angular/http’;
import { HttpClientModule, HttpClient } from ‘@angular/common/http’;
import {
WpApiModule,
WpApiLoader,
WpApiStaticLoader
} from ‘wp-api-angular’;

WpApiModule should also be added to the imports block. Note that we must use an exported factory for AoT compilation or Ionic:

// … imports

@NgModule({
declarations: [
// … omitted
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule, // <—
WpApiModule.forRoot({ // <—
provide: WpApiLoader,
useFactory: (WpApiLoaderFactory),
deps: [Http]
})

]
// …
})

Here’s the factory itself:

export function WpApiLoaderFactory(http: Http) {
return new WpApiStaticLoader(http, ‘http://YOUR_DOMAIN_HERE/wp-json/wp/v2/’, ”);
}

Don’t forget to provide your own domain name here!

Lastly, let’s also add some imports to the app.components.ts file:

import { Component } from ‘@angular/core’;
import { Observable } from ‘rxjs’;
import { NgForm } from ‘@angular/forms’;
import { HttpClientModule, HttpClient } from ‘@angular/common/http’;
import { Headers } from ‘@angular/http’;

// …

We’ll need NgForm to craft forms, HTTP modules to interact with the API and Headers to authenticate the client.

The initial setup is done and we can proceed to the next section.

Authentication

Before interacting with the API, we need to introduce an authentication mechanism. As I already mentioned above, a token-based authentication will be employed, so let’s add a token variable to the app.components.ts:

export class AppComponent {
token = null;
// …
}

Also, tweak the app.component.html file by adding a new block:

<div>
<app-authentication [(token)]=’token’></app-authentication>
</div>

In order for this to work, a separate component is required so generate it now:

ng generate component authentication

Import the necessary modules inside the src/app/authentication/authentication.component.ts file:

import { Component, OnInit, Input, Output, EventEmitter } from ‘@angular/core’;
import { HttpClientModule, HttpClient } from ‘@angular/common/http’;
// …

The authentication process is going to be very simple: a user should enter their login and password, submit the form, and a special token will be returned if the credentials are correct. This token will then be utilized to perform API requests. Therefore, let’s draft a user and add input and ouput for the AuthenticationComponent:

// …
export class AuthenticationComponent implements OnInit {
user = {
login: ”,
password: ”
}
@Input() token;
@Output() tokenChange = new EventEmitter<string>();

// …
}

Of course, you may define the user as a model, but for the purposes of this demo it’s not mandatory. As for the constructor, pass the HttpClient to it:

// …
constructor( private http: HttpClient ) { }

Next code the auth method. It’s as simple as sending a POST request to the proper URL with the credentials and waiting for the response:

// …
auth() {
this.http.post(‘http://YOUR_DOMAIN/wp-json/jwt-auth/v1/token’, {
username: this.user.login,
password: this.user.password
}).subscribe((data) => {
if (data[‘token’]) { // if token is returned
this.token = data[‘token’];
this.tokenChange.emit(this.token);
}
});
}

Once again, don’t forget to insert your domain name into the URL.

The component is ready, and the last thing to do in this section is create the corresponding form. It should be displayed only if the token is null. When the form is submitted, the auth method should be called:

<form *ngIf=’token == null’ (ngSubmit)=’auth()’>
</form>

Flesh the form out by adding two fields and a Submit button:

<form *ngIf=’token == null’ (ngSubmit)=’auth()’>
<div class=’form-group’>
<label for=’login’>Login</label>
<input type=’text’ class=’form-control’ [(ngModel)]=’user.login’ name=’login’ id=’login’ required>
</div>

<div class=’form-group’>
<label for=’password’>Password</label>
<input type=’password’ class=’form-control’ [(ngModel)]=’user.password’ name=’password’ id=’password’ required>
</div>

<button type=”submit” class=”btn btn-success”>Submit</button>
</form>

That’s it! The authentication feature is finished, and we may start playing with the API itself.

Continue reading %Connecting Angular and the WordPress API with wp-api-angular%

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *