I am currently in the process of developing a frontend for a blog. My main objective is to retrieve an array of posts from the API, then make additional API calls for each post to fetch the featured image objects and attach them to their respective parent Post objects. Finally, I aim to return the complete array of Post objects. I have encountered challenges in determining the most effective approach using Observables.
This is what I have accomplished thus far:
export class PostService {
private apiAddress: string = '/wp-json/wp/v2/posts';
private logger: Logger;
constructor (private httpService: HttpService, private loggerService: LoggerService) {
this.logger = loggerService.newLogger('PostService');
}
getPosts(category: Category, page: number = 1, pageSize: number = 10): Observable<Post[]> {
this.logger.log(`getPosts(id:${category.id}, ${page}, ${pageSize}) returned`);
return this.httpService.get(`${this.apiAddress}?categories=${category.id}&page=${page}&per_page=${pageSize}&orderby=date&order=desc`).map<Response, Post[]>((res) => {
let posts:Post[] = [];
let body = res.json();
for (var i = 0; i < body.length; i++) {
posts.push(new Post(body[i]));
}
this.logger.log(`getPosts(id:${category.id}, ${page}, ${pageSize}) returned ${posts.length} posts`);
return posts;
});
}
}
This is my vision of what I would like to achieve:
export class PostService {
private apiAddress: string = '/wp-json/wp/v2/posts';
private logger: Logger;
constructor (private httpService: HttpService, private loggerService: LoggerService) {
this.logger = loggerService.newLogger('PostService');
}
getPosts(category: Category, page: number = 1, pageSize: number = 10): Observable<Post[]> {
this.logger.log(`getPosts(id:${category.id}, ${page}, ${pageSize}) returned`);
return this.httpService.get(`${this.apiAddress}?categories=${category.id}&page=${page}&per_page=${pageSize}&orderby=date&order=desc`).map<Response, Post[]>((res) => {
let posts:Post[] = [];
let body = res.json();
for (var i = 0; i < body.length; i++) {
posts.push(new Post(body[i]));
}
this.logger.log(`getPosts(id:${category.id}, ${page}, ${pageSize}) returned ${posts.length} posts`);
return posts;
}).forEach((post, done) => {
this.httpService.get(`/wp-json/wp/v2/media/${post.featured_media}`).map<Request, Media>((res) => {
let body = res.json();
post.featured_image = new Media(body);
done(post);
});
});
}
}
I recognize that my understanding of Observables may be flawed. Any feedback would be greatly appreciated. Thank you!