-
Notifications
You must be signed in to change notification settings - Fork 0
/
posts.service.ts
88 lines (73 loc) · 2.4 KB
/
posts.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
84
85
86
87
88
import { Injectable } from "@angular/core";
import { Subject } from "rxjs";
import { map } from "rxjs/operators";
import { HttpClient } from "@angular/common/http";
import { Router } from '@angular/router';
import { Post } from "./post.model";
@Injectable({ providedIn: "root" })
export class PostsService {
private posts: Post[] = [];
private postsUpdated = new Subject<Post[]>();
constructor(private http: HttpClient,private router: Router) { }
getPosts() {
this.http
.get<{ message: string; posts: any }>(
"http:///localhost:3000/api/posts"
)
.pipe(map((postData) => {
return postData.posts.map(post => {
return {
title: post.title,
content: post.content,
id: post._id
}
})
}))
.subscribe(transformedPosts => {
this.posts = transformedPosts;
this.postsUpdated.next([...this.posts]);
});
}
getPostUpdateListener() {
return this.postsUpdated.asObservable();
}
getPost(id: string){
// return {...this.posts.find(p => p.id === id)}
return this.http.get<{ _id:string, title:string, content: string }>("http://localhost:3000api/posts/"+id)
}
addPost(title: string, content: string) {
const post: Post = { id: null, title: title, content: content };
this.http
.post<{ message: string, postId: string }>("http://localhost:3000/api/posts", post)
.subscribe(responseData => {
const id = responseData.postId;
post.id = id;
this.posts.push(post);
this.postsUpdated.next([...this.posts]);
this.router.navigate(["/"]);
});
}
updatePost(id: string, title:string, content: string){
const post: Post = {
id: id,
title: title,
content: content
}
this.http.put("http://localhost:3000/api/posts/" + id, post).subscribe(response=>{
const updatedPosts = [...this.posts];
const oldPostIndex = updatedPosts.findIndex(p=> p.id ===post.id);
updatedPosts[oldPostIndex] = post;
this.posts = updatedPosts
this.postsUpdated.next([...this.posts]);
this.router.navigate(["/"])
})
}
deletePost(postId: string) {
this.http.delete("http://localhost:3000/api/posts/" + postId)
.subscribe(() => {
const updatedPosts = this.posts.filter(post => post.id !== postId);
this.posts = updatedPosts;
this.postsUpdated.next([...this.posts])
})
}
}