Skip to content

Instantly share code, notes, and snippets.

@rahulsunil2
Created March 30, 2021 04:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rahulsunil2/7272b8ad5f420e0de4175910ee6a7aff to your computer and use it in GitHub Desktop.
Save rahulsunil2/7272b8ad5f420e0de4175910ee6a7aff to your computer and use it in GitHub Desktop.
Post Service - Angular
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