import { Injectable } from '@angular/core'; import { Http, Headers } from '@angular/http'; import 'rxjs'; export class Comment { constructor( public _id: string, public message: string, public name: string, public email: string, public parent_id: string, public replying: boolean, public unique_id: string, public upvotes: number, public downvotes: number ){} } @Injectable() export class CommentService { public config: any; constructor(private http: Http) {} getComments() { return this.http.get(this.commentsUrl()) .toPromise() .then(response => response.json() as Comment[]) .catch(this.handleError); } getCommentsWithReplies() { console.log("Inside comment.service >> getCommentsWithReplies"); return this.http.get(this.apiUrl()+'/commentsWithReplies') .toPromise() .then(response => response.json() as Comment[]) .catch(this.handleError); } save(comment: Comment): Promise { if(comment._id) { return this.put(comment); } else { return this.post(comment); } } // Add new comment private post(comment: Comment): Promise { let headers = new Headers({ 'Content-Type': 'application/json' }); return this.http .post(this.commentsUrl(), JSON.stringify(comment), { headers: headers }) .toPromise() .then(response => response.json()) .catch(this.handleError); } // Update existing Comment private put(comment: Comment) { let headers = new Headers({ 'Content-Type': `application/json` }); let url = `${this.commentsUrl()}/${comment._id}`; return this.http .put(url, JSON.stringify(comment), { headers: headers }) .toPromise() .then( () => comment ) .catch( this.handleError); } private handleError(error: any) { console.log('An error occurred: '); console.log(error); return Promise.reject(error.message || error); } private apiUrl() { return this.config.server_ip_addr+'/api'; } private commentsUrl() { return this.apiUrl()+'/comments'; } /* Below function is commented as it is meant for admin purpose delete(comment: Comment) { let headers = new Headers(); headers.append('Content-Type', 'application/json'); let url = `${this.commentsUrl()}/${comment._id}`; return this.http .delete(url, { headers: headers }) .toPromise() .catch(this.handleError); } */ /** Below function is added for Demo purpose only; For production use, it SHOULD BE commented out OR Removed */ clearComments():any { let headers = new Headers(); headers.append('Content-Type', 'application/json'); let url = `${this.commentsUrl()}/clear/*`; return this.http .delete(url, { headers: headers }) .toPromise() .catch(this.handleError); } }