Angular WordPress Module
This library is designed to make it easy for your Angular application to request specific resources from a WordPress install.
Requirments
Wordpress installation and WP API v2 plugin activated.
Installation
Install it with npm
npm install ng2-wp-api --save
Table of Contents
## Features
This library is very flexible and easy to use, you will find everything you need included out of the box:
## Abstract
Services:
WpService
One service for all operations (Access/Authenticate/Configure).
Components:
<wp-collection>
Inputs: args, endpoint - Output: collection response.<wp-model>
Inputs: id, args, endpoint - Output: model response.
Helper Classes:
WpPost
Useful class for posts and pages (contains functions for accessing embedded posts).WpUser
Interface for user response.WpQueryArgs
Class for creating query arguments for collection/model.WpEndpoint
List of default endpoints and their addresses.
Default Endpoints are : posts
, pages
, users
, categories
, tags
, taxonomies
, statuses
, comments
, media
WpService
├── config
| ├── baseUrl ** Set WordPress URL
| ├── timeOut ** Http requests timeout
| ├── loading ** Listener for requests loading state
| ├── errors ** Listener for requests errors
|
├── discover(url) ** Discover if a URL has a valid API
|
├── link(url) ** Http Getter with the benefits of loading and errors observables.
| Useful for getting data from external resources
|
├── collection()
| ├── endpoint(ep)
| ├── get(args?) ** Get Collection of endpoint type.
| ├── more() ** Get Next page collection combined with any previous ones.
| ├── next() ** Get Next page collection.
| ├── prev() ** Get Prev page collection.
|
├── model()
| ├── endpoint(ep)
| ├── get(id, args?) ** Get Model by Id.
| ├── add(body) ** Add Model to WP.
| ├── update(id, body) ** Update Model by Id.
| ├── delete(id) ** Delete Model by Id.
|
├── auth()
| ├── basic(username, password) ** Basic authentication, returns loggedInUser.
| ├── cookies() ** Cookies authentication, returns loggedInUser.
| ├── logout() ** Removes authentication info from all requests.
## Usage
Add WordPressModule
to NgModule imports
array.
import { WordPressModule } from 'ng2-wp-api';
@NgModule({
imports: [
WordPressModule
]
})
### Initialization
Set your WordPress base url in the root component
constructor(wpService: WpService){
}
ngOnInit(){
wpService.config.baseUrl = "http://localhost/wordpress";
wpService.config.loading.subscribe(...);
wpService.config.errors.subscribe(...);
}
See [Initializing example](/examples/Initilizing WP Service.ts).
After initializing, you can either consume the library as a service, or as a component.
## Using the service
Import WpService
in component constructor
Import WpEndpoint
to get the desired endpoint address
import {WpService} from "ng2-wp-api";
@Component({...})
export class testComponent {
constructor(private wpService: WpService) {
}
}
**For collection:**
A basic example of fetching 6 embedded posts:
import {WpService,WpEndpoint,WpQueryArgs,CollectionResponse} from "ng2-wp-api";
.
.
var endpoint = WpEndpoint.posts;
var args = new WpQueryArgs({
perPage: 6,
embed: true
});
this.wpService.collection()
.endpoint(endpoint)
.get(args)
.subscribe((res: CollectionResponse) => {
if(res.error){
console.log(res.error);
}
else{
this.data = res.data;
this.pagination = res.pagination;
}
});
See [WpService Collection example](/examples/Collection using the service.ts)
**For model:**
var endpoint = WpEndpoint.posts;
this.wpService.model()
.endpoint(endpoint)
.get(id)
.subscribe((res: ModelResponse) => {
if(res.error){
console.log(res.error);
}
else{
this.data = res.data;
}
});
See [WpService Model example](/examples/Model using the service.ts)
## Using the components
**For collection:**
<wp-collection [args]="args" [endpoint]="endpoint" (response)="wpResponse($event)">
</wp-collection>
WpCollection component gets a new response automatically when the input [args]
value has set/changed.
See [Collection Component example](/examples/Collection using the component.ts)
NOTE: Make sure enableProdMode()
is called to avoid onChanges
error.
**For model:**
<wp-model [id]="id" [endpoint]="endpoint" (response)="wpResponse($event)">
<wp-model>
WpModel component gets a new response automatically when the input [id]
value has set/changed.
See [Model Component example](/examples/Model using the component.ts)
## Direct Link
If you want to do a GET
request for any URL, Use WpService.link(url).subscribe(...)
to get the advantage of error and loading notifiers.
## Add/Update/Delete
wpService.model().posts().add(body);
wpService.model().pages().update(pageId, body);
wpService.model().users().delete(userId);
## Authentication
this.wpService.auth().basic('username', 'password').subscribe(
(loggedInUser: WpUser)=> {
console.log(loggedInUser);
});
this.wpService.auth().cookies().subscribe(
(loggedInUser: WpUser)=> {
console.log(loggedInUser);
});
## Embedded Responses
Usually when displaying a post, you want to display post's featured image, categories, tags, author and comments.
The normal post response contains only the Id references which you will have to request each one of them individually.
Embedded responses are very useful to reduce the amount of http requets. you will get all the information you need in one response.
Embedding is triggered by setting the _embed=true
in WpQueryArgs, check Linking and Embedding
And now WpPost
class will be useful to access the following properties:
post ** the original object
id() ** post id
title() ** post title
content() ** post content
excerpt() ** post excerpt without the (read more) link
date() ** post date
type() ** post type
categories() ** post categories array
tags() ** post tags array
author() ** post author object (WpUser)
featuredMedia() ** to check if a post has a featured image
featuredImageUrl(size) ** to get featured image by the size, ("full", large", "medium") or
any other valid size you have in your WP
other properties can be accessed from the original post
object.
var wpPost = new WpPost(originalPost);
wpPost.post.propertyName
where wpPost.post
= originalPost
, See WpPost class source code
## Hints
## Issues
If you identify any errors in the library, or have an idea for an improvement, please open an issue. I am excited to see what the community thinks of this project, and I would love your input!
## Author
Murhaf Sousli
## License