Kevin Shah
Kevin Shah

Reputation: 21

how to delete particular record based on firebase json key

HtmlCode where data are display. Key is passed as a parameter

<div class="col-xs-12 col-md-6 col-md-offset-3" *ngIf="loadedPosts.length >= 1>
  <ul class="list-group">
    <li class="list-group-item" *ngFor="let post of loadedPosts">
      <h3>Title: {{ post.title}}</h3>
      <span>Content: {{ post.content}}</span>
      <p> <a (click)="onDeletePost(post.id)" style="cursor: pointer;">Delete</a></p>
    </li>
  </ul>
</div>

On Fetch Posts:

 onFetchPosts() {
    this.isLoading = true;

    this.postService.fetchPosts().subscribe(
        (posts)=>{
        this.isLoading = false;
        this.loadedPosts = posts;
        },(error)=>{
          this.error = error.error;
        }
    );
  }

Json key as an argument

On Delete Post:

  onDeletePost(key:string) {
    if(confirm('Are you sure?')){
        this.postService.deletePost(key).subscribe(
          (responseData)=>{
            console.log(responseData);
            this.onFetchPosts();  
          }
        );
      }
  }

    deletePost(key:string) {
        return this.http.delete<void>(
            'https://ng-complete-guide-257c0.firebaseio.com/posts.json',{
                params: new HttpParams().set('name', key)
            }// even passing parameter it clears all record instead of particular record 
        );    
    }

Upvotes: 0

Views: 773

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

When you fire a HTTP DELETE request against 'https://ng-complete-guide-257c0.firebaseio.com/posts.json, the database will delete the entire posts node. If you want to delete a specific post, you need to fire the delete request against 'https://ng-complete-guide-257c0.firebaseio.com/posts/yourpostkey.json.

If you don't know the key of the post to delete, you will first have to execute a query to determine that key.

Upvotes: 1

Related Questions