Collection - MurhafSousli/ngx-wordpress GitHub Wiki

Use @WpCollection decorator whenever you want to get a list of data (posts, categories, tags, users ...etc)

WpCollection Decorator

@WpCollection(endpoint: string, query?: WpQuery)
  • endpoint: Required parameter to set the endpoint target, e.g. posts
  • query: Optional parameter to set the default query for collection requests

WpCollection Example

Get a list of posts

<div *ngIf="posts.state | async; let state">

  <span *ngIf="state.loading" class="spinner">Loading...</span>
    
  <span *ngIf="state.error" class="error">{{ state.error.message }}</span>
        
  <div *ngIf="state.data" class="post">
     <div class="post-title">{{ state.data.title }}</div>
     <div class="post-content" [innerHTML]="state.data.content"></div>
  </div>
</div>

Here we subscribed to posts.state | async in the template, and got back a state { data, loading, pagination, error }

import { Component } from '@angular/core';
import { WpCollection, WpCollectionRef } from '@ngx-wordpress/core';

@Component({
  selector: 'app-collection-page',
  templateUrl: 'app-collection-page.html'
})
export class CollectionPageComponent {

  @WpCollection('posts')
  posts: WpCollectionRef;

  ngOnInit() {
    // Fetch the data from WP API
    this.posts.get().subscribe();
  }
}

Alternatively, you can subscribe to each state property individually

<span *ngIf="posts.loading | async" class="spinner">Loading...</span>

<span *ngIf="posts.error | async; let error" class="error">{{error.message}}</span>

<div *ngIf="posts.data | async; let post" class="post">
   <div class="post-title">{{ post.title }}</div>
   <div class="post-content" [innerHTML]="post.content"></div>
</div>

WpCollectionRef API

Name Description
state Stream that emits collection state
data Stream that emits collection data array
pagination Stream that emits collection pagination state
loading Stream that emits collection loading state
error Stream that emits when an error occurs
get(query?) Get a collection of objects
more() Get the collection of the next page combined with the existing one
next() Get the collection of the next page
prev() Get the collection of the previous page
destroy() Closes the state stream and un-subscribers all its subscriptions
⚠️ **GitHub.com Fallback** ⚠️