Let's perform the following steps to load real API data into our blog service:
- First, we will need to provide our Blogger API key to our application's /src/environments/environment.ts configuration:
export const environment = {
production: false,
bloggerAPIKey: 'YOUR UNIQUE API KEY'
};
- Next, we will overhaul our /src/app/posts/blog-posts.service.ts service to load our blog post data from an external URL and resolve the response into a promise of BlogPost model result:
import { Injectable } from '@angular/core';
import {BlogPost} from './blog-post';
import {Http} from '@angular/http';
import { environment } from '../../environments/environment';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class BlogPostsService {
private apiHostUrl = 'https://www.googleapis.com';
private blogUrl = this.apiHostUrl +
'/blogger/v3/blogs/7159470537406093899';
private postsUrl = this.blogUrl + '/posts?key=' +
environment.bloggerAPIKey;
constructor(private http: Http) {}
getPosts(): Promise<BlogPost[]> {
return this.http.get(this.postsUrl)
.toPromise()
.then((response) => {
let posts = response.json().items;
console.log(posts);
return posts as BlogPost[]
})
}
}
- Finally, we'll update our /src/app/posts/post-list.component.html template to use the displayName user property instead of our previous custom function. We'll also inline the HTML content of the blog post using the innerHTML directive, as follows:
<section class="row" *ngFor="let post of posts; let i = index;">
<div class="col col-sm-12">
<div class="card">
<div class="card-header">
<small class="pull-left">
Posted - {{ post.published | date:'shortDate' }}
</small>
<small class="pull-right">
{{post.author.displayName}}
</small>
</div>
<div class="card-block">
<h4 class="card-title">{{post.title}}</h4>
<p class="card-text" [innerHTML]=post.content></p>
</div>
</div>
</div>
</section>
- Now, we can visit our /posts page and see that our blog posts are full of content from the official Angular blog.