Skip to content

Instantly share code, notes, and snippets.

@peterbsmyth
Created March 25, 2018 02:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterbsmyth/1efb3b1438fe43fdafd806829013438c to your computer and use it in GitHub Desktop.
Save peterbsmyth/1efb3b1438fe43fdafd806829013438c to your computer and use it in GitHub Desktop.
api.service.ts for https://blog.upstate.agency
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { TransferState, makeStateKey } from '@angular/platform-browser';
import { of } from 'rxjs/observable/of';
import { tap } from 'rxjs/operators';
export const POST_KEY = makeStateKey('posts');
@Injectable()
export class ApiService {
constructor(
private http: HttpClient,
private state: TransferState,
) { }
getPosts() {
const posts = this.state.get(POST_KEY, null as any);
if (posts) {
return of(posts);
}
return this.http.get('https://jsonplaceholder.typicode.com/posts/')
.pipe(
tap((res) => this.state.set(POST_KEY, res as any))
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment