如何在 Ionic 应用程序页面中显示特定类别的帖子
How to display posts from specific category in Ionic App Page
我想显示来自特定类别的所有 post,例如 Works,id 在我的 wordpress 站点中 1我的 Ionic 应用程序中的 WorksPage。
下面是在 page/Home 主屏幕上显示所有最近 post 的代码。
HOMEPAGE/ALL -- home.ts
import { Component } from '@angular/core';
import { PostPage } from '../post/post';
import { NavController, LoadingController, NavParams } from 'ionic-angular';
import { WordpressService } from '../../services/wordpress.service';
import { AuthenticationService } from '../../services/authentication.service';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
posts: Array<any> = new Array<any>();
morePagesAvailable: boolean = true;
loggedUser: boolean = false;
categoryId: number;
categoryTitle: string;
constructor(
public navCtrl: NavController,
public navParams: NavParams,
public loadingCtrl: LoadingController,
public wordpressService: WordpressService,
public authenticationService: AuthenticationService
) {}
ionViewWillEnter() {
this.authenticationService.getUser()
.then(
data => this.loggedUser = true,
error => this.loggedUser = false
);
this.morePagesAvailable = true;
//if we are browsing a category
this.categoryId = this.navParams.get('id');
this.categoryTitle = this.navParams.get('title');
if(!(this.posts.length > 0)){
let loading = this.loadingCtrl.create();
loading.present();
this.wordpressService.getRecentPosts(this.categoryId)
.subscribe(data => {
for(let post of data){
post.excerpt.rendered = post.excerpt.rendered.split('<a')[0] + "</p>";
this.posts.push(post);
}
loading.dismiss();
});
}
}
postTapped(event, post) {
this.navCtrl.push(PostPage, {
item: post
});
}
doRefresh(refresher) {
console.log('Begin async operation', refresher);
setTimeout(() => {
console.log('Async operation has ended');
refresher.complete();
}, 2000);
}
doInfinite(infiniteScroll) {
let page = (Math.ceil(this.posts.length/10)) + 1;
let loading = true;
this.wordpressService.getRecentPosts(this.categoryId, page)
.subscribe(data => {
for(let post of data){
if(!loading){
infiniteScroll.complete();
}
post.excerpt.rendered = post.excerpt.rendered.split('<a')[0] + "</p>";
this.posts.push(post);
loading = false;
}
}, err => {
this.morePagesAvailable = false;
})
}
/*logOut(){
this.authenticationService.logOut()
.then(
res => this.navCtrl.push(LoginPage),
err => console.log('Error in log out')
)
}
goToLogin(){
this.navCtrl.push(LoginPage);
}*/
}
home.html
<ion-list *ngFor="let post of posts" (click)="postTapped($event, post)" class="cardList">
<ion-card-content class="innerContent">
<ion-grid>
<ion-row class="entityParams">
<ion-col class="img" col-2><img id="roundpic" src="{{post.images.medium}}" class="thumbs" />
</ion-col>
<ion-col col-10 class="ParamsInner">
<ion-row class="entity">{{post.custom_fields.entity}} </ion-row>
<ion-row class="method"><ion-icon name="clipboard"></ion-icon> {{post.custom_fields.method}}</ion-row>
</ion-col>
</ion-row>
<ion-row class="ptb">
<span [innerHTML]="post.title.rendered" class="postTitle"></span>
</ion-row>
<ion-row class="cardbottom">
<ion-col col-8 class="ref_number dotted-spaced-ref"> <ion-icon name="radio-button-on"></ion-icon> {{post.custom_fields.ref_number}} </ion-col>
<ion-col col-4 class="deadline dotted-spaced-dline"><ion-icon name="calendar"></ion-icon> Ending:<br />{{post.custom_fields.deadline}}</ion-col>
</ion-row>
</ion-grid>
</ion-card-content>
</ion-list>
配置file.ts
//config constants
export const WORDPRESS_URL = 'http://www.example.com/wp/';
export const WORDPRESS_REST_API_URL = WORDPRESS_URL + 'wp-json/wp/v2/';
我尝试将下面的代码放入我的 works.ts 文件中,但它显示所有最近的 posts 而不是 posts特定类别(作品)
import { Component } from '@angular/core';
import { PostPage } from '../post/post';
import { IonicPage, NavController, LoadingController, NavParams } from 'ionic-angular';
import { WordpressService } from '../../services/wordpress.service';
import { AuthenticationService } from '../../services/authentication.service';
/**
* Generated class for the WorksPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
@IonicPage()
@Component({
selector: 'page-works',
templateUrl: 'works.html',
})
export class WorksPage {
posts: Array<any> = new Array<any>();
morePagesAvailable: boolean = true;
loggedUser: boolean = false;
categoryId: number;
categoryTitle: string;
constructor(
public navCtrl: NavController,
public navParams: NavParams,
public loadingCtrl: LoadingController,
public wordpressService: WordpressService,
public authenticationService: AuthenticationService
) {}
constructor(public navCtrl: NavController, public navParams: NavParams) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad WorksPage');
//if we are browsing a category
this.categoryId = this.navParams.get(1);
this.categoryTitle = this.navParams.get('title');
if(!(this.posts.length > 0)){
let loading = this.loadingCtrl.create();
loading.present();
this.wordpressService.getRecentPosts(this.categoryId)
.subscribe(data => {
for(let post of data){
post.excerpt.rendered = post.excerpt.rendered.split('<a')[0] + "</p>";
this.posts.push(post);
}
loading.dismiss();
});
}
}
postTapped(event, post) {
this.navCtrl.push(PostPage, {
item: post
});
}
doInfinite(infiniteScroll) {
let page = (Math.ceil(this.posts.length/10)) + 1;
let loading = true;
this.wordpressService.getRecentPosts(this.categoryId, page)
.subscribe(data => {
for(let post of data){
if(!loading){
infiniteScroll.complete();
}
post.excerpt.rendered = post.excerpt.rendered.split('<a')[0] + "</p>";
this.posts.push(post);
loading = false;
}
}, err => {
this.morePagesAvailable = false;
})
}
}
添加编辑
services.ts 文件
中使用了此代码
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import * as Config from '../config';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/forkJoin';
@Injectable()
export class WordpressService {
constructor(public http: Http){}
getRecentPosts(categoryId:number, page:number = 1){
//if we want to query posts by category
let category_url = categoryId? ("&categories=" + categoryId): "";
return this.http.get(
Config.WORDPRESS_REST_API_URL
+ 'posts?page=' + page
+ category_url)
.map(res => res.json());
}
getComments(postId:number, page:number = 1){
return this.http.get(
Config.WORDPRESS_REST_API_URL
+ "comments?post=" + postId
+ '&page=' + page)
.map(res => res.json());
}
getAuthor(author){
return this.http.get(Config.WORDPRESS_REST_API_URL + "users/" + author)
.map(res => res.json());
}
getPostCategories(post){
let observableBatch = [];
post.categories.forEach(category => {
observableBatch.push(this.getCategory(category));
});
return Observable.forkJoin(observableBatch);
}
getCategory(category){
return this.http.get(Config.WORDPRESS_REST_API_URL + "categories/" + category)
.map(res => res.json());
}
createComment(postId, user, comment){
let header: Headers = new Headers();
header.append('Authorization', 'Bearer ' + user.token);
return this.http.post(Config.WORDPRESS_REST_API_URL + "comments?token=" + user.token, {
author_name: user.displayname,
author_email: user.email,
post: postId,
content: comment
},{ headers: header })
.map(res => res.json());
}
}
如果您查看 WordPress rest api documentation,它说您可以在请求中发送 categories
参数:
所以 url 将是这样的:
https://www.example.com/wp-json/wp/w2/posts?categories=1
如果作品类别有 term_id 1
,则该类别中的所有帖子应该只有 return
我想显示来自特定类别的所有 post,例如 Works,id 在我的 wordpress 站点中 1我的 Ionic 应用程序中的 WorksPage。
下面是在 page/Home 主屏幕上显示所有最近 post 的代码。 HOMEPAGE/ALL -- home.ts
import { Component } from '@angular/core';
import { PostPage } from '../post/post';
import { NavController, LoadingController, NavParams } from 'ionic-angular';
import { WordpressService } from '../../services/wordpress.service';
import { AuthenticationService } from '../../services/authentication.service';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
posts: Array<any> = new Array<any>();
morePagesAvailable: boolean = true;
loggedUser: boolean = false;
categoryId: number;
categoryTitle: string;
constructor(
public navCtrl: NavController,
public navParams: NavParams,
public loadingCtrl: LoadingController,
public wordpressService: WordpressService,
public authenticationService: AuthenticationService
) {}
ionViewWillEnter() {
this.authenticationService.getUser()
.then(
data => this.loggedUser = true,
error => this.loggedUser = false
);
this.morePagesAvailable = true;
//if we are browsing a category
this.categoryId = this.navParams.get('id');
this.categoryTitle = this.navParams.get('title');
if(!(this.posts.length > 0)){
let loading = this.loadingCtrl.create();
loading.present();
this.wordpressService.getRecentPosts(this.categoryId)
.subscribe(data => {
for(let post of data){
post.excerpt.rendered = post.excerpt.rendered.split('<a')[0] + "</p>";
this.posts.push(post);
}
loading.dismiss();
});
}
}
postTapped(event, post) {
this.navCtrl.push(PostPage, {
item: post
});
}
doRefresh(refresher) {
console.log('Begin async operation', refresher);
setTimeout(() => {
console.log('Async operation has ended');
refresher.complete();
}, 2000);
}
doInfinite(infiniteScroll) {
let page = (Math.ceil(this.posts.length/10)) + 1;
let loading = true;
this.wordpressService.getRecentPosts(this.categoryId, page)
.subscribe(data => {
for(let post of data){
if(!loading){
infiniteScroll.complete();
}
post.excerpt.rendered = post.excerpt.rendered.split('<a')[0] + "</p>";
this.posts.push(post);
loading = false;
}
}, err => {
this.morePagesAvailable = false;
})
}
/*logOut(){
this.authenticationService.logOut()
.then(
res => this.navCtrl.push(LoginPage),
err => console.log('Error in log out')
)
}
goToLogin(){
this.navCtrl.push(LoginPage);
}*/
}
home.html
<ion-list *ngFor="let post of posts" (click)="postTapped($event, post)" class="cardList">
<ion-card-content class="innerContent">
<ion-grid>
<ion-row class="entityParams">
<ion-col class="img" col-2><img id="roundpic" src="{{post.images.medium}}" class="thumbs" />
</ion-col>
<ion-col col-10 class="ParamsInner">
<ion-row class="entity">{{post.custom_fields.entity}} </ion-row>
<ion-row class="method"><ion-icon name="clipboard"></ion-icon> {{post.custom_fields.method}}</ion-row>
</ion-col>
</ion-row>
<ion-row class="ptb">
<span [innerHTML]="post.title.rendered" class="postTitle"></span>
</ion-row>
<ion-row class="cardbottom">
<ion-col col-8 class="ref_number dotted-spaced-ref"> <ion-icon name="radio-button-on"></ion-icon> {{post.custom_fields.ref_number}} </ion-col>
<ion-col col-4 class="deadline dotted-spaced-dline"><ion-icon name="calendar"></ion-icon> Ending:<br />{{post.custom_fields.deadline}}</ion-col>
</ion-row>
</ion-grid>
</ion-card-content>
</ion-list>
配置file.ts
//config constants
export const WORDPRESS_URL = 'http://www.example.com/wp/';
export const WORDPRESS_REST_API_URL = WORDPRESS_URL + 'wp-json/wp/v2/';
我尝试将下面的代码放入我的 works.ts 文件中,但它显示所有最近的 posts 而不是 posts特定类别(作品)
import { Component } from '@angular/core';
import { PostPage } from '../post/post';
import { IonicPage, NavController, LoadingController, NavParams } from 'ionic-angular';
import { WordpressService } from '../../services/wordpress.service';
import { AuthenticationService } from '../../services/authentication.service';
/**
* Generated class for the WorksPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
@IonicPage()
@Component({
selector: 'page-works',
templateUrl: 'works.html',
})
export class WorksPage {
posts: Array<any> = new Array<any>();
morePagesAvailable: boolean = true;
loggedUser: boolean = false;
categoryId: number;
categoryTitle: string;
constructor(
public navCtrl: NavController,
public navParams: NavParams,
public loadingCtrl: LoadingController,
public wordpressService: WordpressService,
public authenticationService: AuthenticationService
) {}
constructor(public navCtrl: NavController, public navParams: NavParams) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad WorksPage');
//if we are browsing a category
this.categoryId = this.navParams.get(1);
this.categoryTitle = this.navParams.get('title');
if(!(this.posts.length > 0)){
let loading = this.loadingCtrl.create();
loading.present();
this.wordpressService.getRecentPosts(this.categoryId)
.subscribe(data => {
for(let post of data){
post.excerpt.rendered = post.excerpt.rendered.split('<a')[0] + "</p>";
this.posts.push(post);
}
loading.dismiss();
});
}
}
postTapped(event, post) {
this.navCtrl.push(PostPage, {
item: post
});
}
doInfinite(infiniteScroll) {
let page = (Math.ceil(this.posts.length/10)) + 1;
let loading = true;
this.wordpressService.getRecentPosts(this.categoryId, page)
.subscribe(data => {
for(let post of data){
if(!loading){
infiniteScroll.complete();
}
post.excerpt.rendered = post.excerpt.rendered.split('<a')[0] + "</p>";
this.posts.push(post);
loading = false;
}
}, err => {
this.morePagesAvailable = false;
})
}
}
添加编辑 services.ts 文件
中使用了此代码import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import * as Config from '../config';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/forkJoin';
@Injectable()
export class WordpressService {
constructor(public http: Http){}
getRecentPosts(categoryId:number, page:number = 1){
//if we want to query posts by category
let category_url = categoryId? ("&categories=" + categoryId): "";
return this.http.get(
Config.WORDPRESS_REST_API_URL
+ 'posts?page=' + page
+ category_url)
.map(res => res.json());
}
getComments(postId:number, page:number = 1){
return this.http.get(
Config.WORDPRESS_REST_API_URL
+ "comments?post=" + postId
+ '&page=' + page)
.map(res => res.json());
}
getAuthor(author){
return this.http.get(Config.WORDPRESS_REST_API_URL + "users/" + author)
.map(res => res.json());
}
getPostCategories(post){
let observableBatch = [];
post.categories.forEach(category => {
observableBatch.push(this.getCategory(category));
});
return Observable.forkJoin(observableBatch);
}
getCategory(category){
return this.http.get(Config.WORDPRESS_REST_API_URL + "categories/" + category)
.map(res => res.json());
}
createComment(postId, user, comment){
let header: Headers = new Headers();
header.append('Authorization', 'Bearer ' + user.token);
return this.http.post(Config.WORDPRESS_REST_API_URL + "comments?token=" + user.token, {
author_name: user.displayname,
author_email: user.email,
post: postId,
content: comment
},{ headers: header })
.map(res => res.json());
}
}
如果您查看 WordPress rest api documentation,它说您可以在请求中发送 categories
参数:
所以 url 将是这样的:
https://www.example.com/wp-json/wp/w2/posts?categories=1
如果作品类别有 term_id 1
,则该类别中的所有帖子应该只有 return