Created
December 12, 2016 22:18
-
-
Save zevisert/9d8451488b6810ac9256c5866e1d9d83 to your computer and use it in GitHub Desktop.
Blog Service
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Injectable() | |
export class BlogService { | |
private allPostsUrl = "api/posts"; | |
private singlePostUrl = "api/post/"; | |
private cachedPosts: PostData[]; | |
private cachedPromise: Promise<PostData[]>; | |
// Angular2-jwt nicely attaches the token to every request for us | |
constructor(@Inject(AuthHttp) private http: AuthHttp) { } | |
getPosts(): Promise<PostData[]> { | |
if (this.cachedPosts) { | |
// Have data, return it | |
return Promise.resolve(this.cachedPosts); | |
} | |
else if (this.cachedPromise) { | |
// Don't have data, but have an observable. | |
// A request must be in progress, return the obs | |
return this.cachedPromise; | |
} else { | |
this.cachedPromise = this.http.get(this.allPostsUrl) | |
.toPromise() | |
.then((res: Response) => { | |
this.cachedPosts = res.json() as PostData[]; | |
// Have the data now, don't need the promise | |
this.cachedPromise = null; | |
return this.cachedPosts; | |
}) | |
.catch(this.handleError); | |
return this.cachedPromise; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment