-
Notifications
You must be signed in to change notification settings - Fork 4
/
post.service.ts
83 lines (70 loc) · 2.19 KB
/
post.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/operator/shareReplay';
import 'rxjs/add/operator/map';
export interface Post {
key: string;
body: string;
date: string;
id: string;
image: string;
title: string;
renderedBody?: string;
}
@Injectable()
export class PostService {
url = 'https://fluindotio-website-93127.firebaseio.com/posts.json';
/**
* An object with post keys as keys, and post data as values
*/
postMap: Observable<any>;
/**
* An sorted array of posts with keys directly on the object.
*/
postList: Observable<Post[]>;
private forceRefresher = new Subject();
constructor(private http: Http) {
this.postMap = this.forceRefresher.startWith(null).switchMap(() => this.http.get(this.url)
.map(response => {
let result = response.json();
return result;
})).shareReplay(1);
// Force it to be hot and available for everyone without additional http requests
this.postMap.subscribe(n => n);
// Turn an object into an array, similar to refirebase
this.postList = this.postMap.map(data => {
let list = [];
for (let key of Object.keys(data)) {
let item = data[key];
item.key = key;
// Only include past items
if (!this.isFuture(item)) {
list.push(item);
}
}
list.sort((a, b) => {
if (a.date > b.date) {
return -1;
} else if (b.date > a.date) {
return 1;
} else {
return 0;
}
});
return list;
}).shareResults();
}
refreshData() {
this.forceRefresher.next();
}
isFuture(post: Post) {
if (new Date(post.date + 'T00:00').getTime() > Date.now() || !post.date) {
return true;
} else {
return false;
}
}
}