Skip to content

Instantly share code, notes, and snippets.

@MurhafSousli
Last active February 26, 2017 12:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MurhafSousli/063e4a374ddf0f7fb87ece5e463c9071 to your computer and use it in GitHub Desktop.
Save MurhafSousli/063e4a374ddf0f7fb87ece5e463c9071 to your computer and use it in GitHub Desktop.
ng2-wp-api Getting Collection
import {Component, ViewChild, AfterViewInit} from '@angular/core';
import {WpEndpoint, CollectionDirective, CollectionResponse} from '../../core/wordpress';
@Component({
selector: 'feed-page',
templateUrl: `
<div class="feed" #feed [wpCollection]="postsEndpoint" [wpArgs]="postsArgs">
<ul>
<li *ngFor="let post of posts">{{post.title()}}</li>
</ul>
<button (click)="loadMore()">Load more</button>
</div>
<loading-icon *ngIf="isLoading"></loading-icon>
`
})
export class HomeComponent implements AfterViewInit {
/** Posts Endpoint */
postsEndpoint = WpEndpoint.posts;
/** Posts Args */
// in case you are using the filter plugin
postsArgs = {
'filter[orderby]': 'rand',
per_page: 10,
_embed: true
};
/** Posts Response */
posts;
/** show loading icon */
postsLoading: boolean = false;
/** Get the directive reference */
@ViewChild(CollectionDirective) feed: CollectionDirective;
ngAfterViewInit() {
this.feed.response.subscribe((res) => {
if (res) {
if (res.error) {
console.log('[Feed Posts]:', res.error);
}
if(!res.data.length){
console.log('[Feed Posts]: Empty');
}
if (res.data) {
this.posts = res.data;
}
/** For pagination use res.pagination */
}
});
/** Show spinner loading */
this.feed.wpLoading.distinctUntilChanged().subscribe((loading) => {
this.postsLoading = loading;
});
}
/** Load more feed on scroll */
loadMore() {
this.feed.more();
/** For pagination use next page and prev page*/
//this.feed.next();
//this.feed.prev();
}
}
@Component({
selector: 'collection-page',
templateUrl: `
<div class="feed" [wpCollection]="postsEndpoint" [wpArgs]="postsArgs" (wpResponse)="postsResponse($event)">
<ul>
<li *ngFor="let post of posts">{{post.title()}}</li>
</ul>
</div>
`
})
export class HomeComponent {
/** Posts Endpoint */
postsEndpoint = WpEndpoint.posts;
/** Posts Args */
// in case you are using the filter plugin
postsArgs = {
'filter[orderby]': 'rand',
per_page: 10,
_embed: true
};
/** Posts Response */
posts;
postResponse(res: CollectionResponse) {
if (res) {
if (res.error) {
console.log('[Collection]:', res.error);
}
if(!res.data.length){
console.log('[Collection]: Empty');
}
if (res.data) {
this.posts = res.data;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment