-
-
Save rahulsunil2/7272b8ad5f420e0de4175910ee6a7aff to your computer and use it in GitHub Desktop.
Post Service - Angular
This file contains 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
import { Injectable } from '@angular/core'; | |
import { Post } from './post.model'; | |
import { Subject } from 'rxjs'; | |
import { HttpClient } from '@angular/common/http'; | |
import { map } from 'rxjs/operators'; | |
@Injectable({providedIn: 'root'}) | |
export class PostsService { | |
private posts: Post[] = []; | |
private postsUpdated = new Subject<Post[]>(); | |
constructor(private http: HttpClient) {} | |
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((transformedData) => { | |
this.posts = transformedData; | |
this.postsUpdated.next([...this.posts]); | |
}); | |
} | |
getPostUpdateListener() { | |
return this.postsUpdated.asObservable(); | |
} | |
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]); | |
})); | |
} | |
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]); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment