Setelah melakukan refactoring, berikutnya kita akan menambahkan fitur untuk melakukan perintah delete. Method yang digunakan adalah http.delete(‘url’);
Buka file post.service.ts, tambahkan method untuk melakukan proses delete.
deletePosts(){
return this.http.delete('https://angular03-f9c9b-default-rtdb.firebaseio.com/posts.json');
}
Kemudian buka file app.component.ts, tambahkan code untuk memanggil method diatas.
onClearPosts() {
this.postSrv.deletePosts().subscribe(()=>{
this.loadedPosts=[];
});
}
Berikut isi lengkap file post.service.ts
import { HttpClient } from "@angular/common/http"; import { Injectable } from "@angular/core"; import { map } from 'rxjs/operators'; import { Post } from "./post.model"; @Injectable({providedIn: "root"}) export class PostService{ constructor(private http: HttpClient){} createPost(title: string, content: string){ const postData: Post = {title: title, content: content} this.http .post<{ name: string }>('https://angular03-f9c9b-default-rtdb.firebaseio.com/posts.json', postData).subscribe( responseData =>{ console.log(responseData); } ); } fetchPosts(){ return this.http .get<{ [key: string]: Post }>('https://angular03-f9c9b-default-rtdb.firebaseio.com/posts.json') .pipe( map (responseData =>{ const postArr : Post[] = []; for (const key in responseData){ if (responseData.hasOwnProperty(key)){ postArr.push({...responseData[key], id: key}); } } return postArr; })); } deletePosts(){ return this.http.delete('https://angular03-f9c9b-default-rtdb.firebaseio.com/posts.json'); } }
File app.component.ts
import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Post } from './post.model'; import { PostService } from './post.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { loadedPosts: Post[] = []; isFetching = false; constructor(private http: HttpClient, private postSrv : PostService) {} ngOnInit() { this.fetchPosts(); } onCreatePost(postData: Post) { this.postSrv.createPost(postData.title, postData.content); } onFetchPosts() { this.fetchPosts(); } onClearPosts() { this.postSrv.deletePosts().subscribe(()=>{ this.loadedPosts=[]; }); } private fetchPosts(){ this.isFetching = true; this.postSrv.fetchPosts().subscribe(posts =>{ this.isFetching = false; this.loadedPosts = posts; }); } }
Sesuai ekspektasi kita sudah berhasil melakukan proses delete.
