How to do it...

Let's follow the steps below to add client-side caching to our blog post service:

  1. First, we'll set up our newly generated /src/app/posts/post-page.ts class to match the schema of the blog post results we get from the Blogger API:
import {BlogPost} from "./blog-post";

export class PostPage {
constructor(
public kind: string,
public nextPageToken: string,
public items: BlogPost[],
public etag: string
) {}
}
  1. Next, we'll add a pageCache property to our /src/app/posts/blog-posts.service.ts service that will work as our service's local cache of blog pages that we've loaded. We will also need writePageToCache and readPageFromCache methods to store PostPage data inside our cache and get it back out:
...
import {PostPage} from "./post-page";

@Injectable()
export class BlogPostsService {
...
private pageCache: { [token: string]: PostPage } = {};

private writePageToCache(token: string, page: PostPage) {
this.pageCache[token] = page as PostPage;
}


private readPageFromCache(token: string): PostPage {
if (this.pageCache[token]) {
return this.pageCache[token];
}

}
...
}
  1. Now, we will need to refactor our BlogPosts service to know when it should load content from the API and when to load it from our local cache. We will use the pageToken parameter as a key to check whether we have a locally cached version of the page. If we have a cached version of the page, we will resolve the promise with that result instead of making an HTTP request. Otherwise, everything will work as it had before:
private requestPosts(params: URLSearchParams = new URLSearchParams()): Promise<any> {
params.set('key', environment.bloggerAPIKey);
return this.http.get(this.postsUrl, {params: params})
.toPromise()
.then((response) => {
return response.json();
})
}

getPosts(pageToken: string = 'first-page'): Promise<BlogPost[]> {
let cachedPage = this.readPageFromCache(pageToken);
if (cachedPage) {
this.nextPageToken = cachedPage.nextPageToken;
return Promise.resolve(cachedPage.items);
} else {
let params: URLSearchParams = new URLSearchParams();
if (pageToken !== 'first-page') params.set('pageToken', pageToken);
return this.requestPosts(params).then((JSON) => {
let posts = JSON.items;
this.nextPageToken = JSON.nextPageToken;
this.writePageToCache(pageToken, JSON);
return posts as BlogPost[]
}).catch(this.handleError);
}
}
  1. When we visit the /posts route of our application the first time, it will request the post data through the API. However, every time after that, it will simply return the post data from the cache without making an unneeded HTTP request.
..................Content has been hidden....................

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