How to do it...

Let's perform the following steps to load real API data into our blog service:

  1. 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'
};
  1. 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[]
})
}
}
  1. 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>
  1. Now, we can visit our /posts page and see that our blog posts are full of content from the official Angular blog.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.37.161