Delete Method In Angular

The delete method is used to delete the resource from a server. Delete request makes a change in the server state. Sending the message on a delete request might cause some services to reject the request but you still send the data to the server using URL Parameter. This delete operation is done using the usual id of this resource. The delete method defines the imported which means that sending that some HTTP delete request multiple times will have the same effect on the server and will not additionally affect the state.

We can perform the delete operation using angular http delete method () . http delete method() URL using HTTP delete method. This is the rest web service used to update any article or information.

Body

This is of any type of object that will be passed to the rest web service server. In our example, we will create an angular class as an article and pass it instantly to the body parameter.

Options

This is optional. This is used to pass the request. Parameter and request headers ETC.

HTTP get()

Return the instance of observable

Step 1

Click here and follow this article on how to add data to the angular. And after completing this article process; you have to follow these article steps which are given below?

Step 2

Go to the .html file and create a form and add a delete button with a field.

Step 3

Then create a click event with the delete function on this button.

Step 4

Then go to the service.ts file and create a delete query in the service.ts file. And return the book URL.

Step 5

Now you have to go to the .ts file and create a function you will create in the delete button in the .html file. And then you have to create a query to delete the element. And then save the all code.

delete.html

<h2>Http client post methood call</h2>
<p *ngIf='datasaved' ngClass='success'>
    Record save successfully
    </p>
    <form [formGroup]='bookForm' (ngSubmit)='onFormSubmit()'>
        <table>
            <tr>
                <td>Name:</td>
                <td> <input formControlName="name"> </td>
            </tr>
            <tr>
                <td>Author:</td>
                <td> <input formControlName="Author"> </td>
            </tr>
            <tr>
                <td>Category:</td>
                <td> <input formControlName="category"> </td>
            </tr>
            <tr>
                <td colspan="2">
                    <button [disabled]="bookForm.invalid">Submit</button>
                </td>
            </tr>
        </table>

    </form>
<h2>View</h2>
<table border="2px">
    <tr>
        <td>Id</td>
        <td>Name</td>

        <td>Cetegory</td>

        <td>Author</td>

        <td>Delete</td>

    </tr>
    <tr *ngFor='let bk of allbooks| async'>
    <td>{{bk.id}}</td>
    <td>{{bk.name}}</td>

    <td>{{bk.category}}</td>

    <td>{{bk.Author}}</td>
    <td><button type="button" (click)='BooktoEdit(bk.id)'>Edit</button></td>

    <td><button type="button" (click)='BookDelete(bk.id)'>Delete</button></td>

</tr>
</table>

delete.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup,FormBuilder,Validators } from '@angular/forms';
import { Observable } from 'rxjs';
import { Book } from '../book';
import { BookService } from '../book.service';

@Component({
  selector: 'app-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.css']
})
export class AddComponent implements OnInit {
title='chaman gautam';
datasaved=false;
bookForm:FormGroup;
allbooks:Observable<Book[]>;
BookitoUpdate=null;

  constructor(private formbuilder:FormBuilder, private bookservice:BookService) { }
ngOnInit(){
  this.bookForm=this.formbuilder.group({
    name:[' ',[Validators.required]],
    Author:[' ',[Validators.required]],
    category:[' ',[Validators.required]]



  });
  this.getsoftBooks();
}

onFormSubmit(){
  this.datasaved=false;
  let book=this.bookForm.value;
  this.createbooks(book);
  this.bookForm.reset();
}
createbooks(book:Book){
  if(this.BookitoUpdate==null){

  this.bookservice.createbook(book).subscribe(book=>{
    this.datasaved=true;
    this.getsoftBooks();

  });
}


}
 getsoftBooks(){
this.allbooks=this.bookservice.getBooksFromStore();
 }

 BookDelete(bookid:string){
   this.bookservice.BookDelete(bookid)
   .subscribe(book=>{
     this.getsoftBooks();
   })
 }
}

service.ts

import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import{Observable } from 'rxjs';
import { Book } from './book';
@Injectable({
  providedIn: 'root'
})
export class BookService {
bookUrl="api/books"

  constructor( private http:HttpClient) { }
  getbookbyid(bookid:string){
    return this.http.get<Book>(this.bookUrl+"/"+bookid)
  }

  createbook(book:Book):Observable<Book>{
    let httpheaders=new HttpHeaders()
    .set('Content-type','application/Json');
    let options={
      headers:httpheaders
    };
    return this.http.post<Book>(this.bookUrl,book,options);
  }


  BookDelete (bookid:String):Observable<number>{
    let httpheaders=new HttpHeaders()
    .set('Content-type','application/Json');
    let options={
      headers:httpheaders
    };
    return this.http.delete<number>(this.bookUrl+"/"+bookid);
  }

  getBooksFromStore():Observable<Book[]>{
    return this.http.get<Book[]>(this.bookUrl);
  }
}

module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import {HttpClientModule } from '@angular/common/http'
import { AppComponent } from './app.component';
import { AddComponent } from './add/add.component';
import { RouterModule, Routes} from '@angular/router';
import{BookService } from './book.service';
import {InMemoryWebApiModule } from 'angular-in-memory-web-api';
import {TestData } from './testdata'

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { ShowdataComponent } from './showdata/showdata.component';
import { CommonModule } from '@angular/common';
import { IfelseComponent } from './ifelse/ifelse.component';
import { SwitchComponent } from './switch/switch.component';
import { LoopsComponent } from './loops/loops.component';
const routes: Routes = [
  {path:'', component:AddComponent},
  { path:'add', component:AddComponent}
];

@NgModule({
  declarations: [
    AppComponent,
    AddComponent,
    ShowdataComponent,
    IfelseComponent,
    SwitchComponent,
    LoopsComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,RouterModule.forRoot(routes),ReactiveFormsModule, FormsModule,
    HttpClientModule, CommonModule,
    InMemoryWebApiModule.forRoot(TestData)
  ],
  providers: [BookService],
  bootstrap: [AddComponent]
})
export class AppModule { }

main.ts

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.error(err));

index.html

<meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-add></app-add>
</body>
</html>

Now go to the terminal and compile this project using the command “ ng serve”. Now you can see that your project compiles successfully.

Now you have to open the browser and hit “localhost: 4200”, and run the project. After a few seconds, you can see that your computer screen will be shown the output.

OUTPUT 

Now you can see that there will be 4 records shown in the table. Now we delete one record from the table and after deleting one record data will be shown like this.

Now you can see that 2nd record will be deleted and 3 records are getting second place in the table. 

Now you have to delete one more record from the table, and after deleting the data will be shown like,

I hope you enjoy this article. 

Follow Chaman Gautam to read more about angular, and follow C# Corner to learn about more technology.