How To Save And View Data Using In-Memory Web API

Post and get operation using In-memory web API

 
Post operation is used to send the data to the server/ save data to the server. When we need to save the data into the server then we use post-operation. Post-operation is used by the HTTP client to save the data into the server. The HTTP client comes with the angular 4.3 version. Before the Angular 4.3 version, we used HTTP for server requests and responses. In the post method, we pass the URL as a string. We can save the data into the body.
 

Http client post()

  • URL - Pass URL as a string where we want to post data.
  • Body - Pass data to be any type as a body to be posted.
  • Option - we can pass options such as headers, parameter,s, etc. this argument is optional.
  • Headers - define HTTP headers for HTTP post requests.
  • Observe - Define whether we want a complete response for body only or event only.
  • Params - Define parameters in URL. The response type of HTTP clients. post is Rxjs Observable which represents over any amount of time.
In the previous article, I told you how to create an in-memory web API, how to use this API in the angular service, and how to use angular service in the angular application.

So we follow the same process step by step,
 
 
Step 1
 
Create a web API. But we have to make a small change in that API for post data using the form.
 
Step 2
 
Create a service using the in-memory web API.
 
Step 3
 
To post the data to the database from the user, create a post method in this service.
 
Step 4
 
Create a component using the command “ ng g component post”.
 
Step 5
 
Go to the module file and register all the decencies, components, modules, services, and import all libraries.
 
Step 6
 
Now you have to go to the post component, import the service and the wrapper class.
 
Step 7
 
Create an object of the wrapper class. In the post-component class.
 
Step 7
 
Create an object of service in the constructor as a private.
 
Step 8
 
Create a post function, and then create a query for posting the data to the database.
 
Step 9
 
After creating post data successfully; you need to create a get function for showing the data into the frontend. To check that your operation is performed there works properly or not.
 
Step 10
 
After creating a get method you have to go to the HTML component and create a form.
 
Step 11
 
You have to create a text field and button in the form. And then create a function event on the button click. But the function name will be the same as which function you create in the component .ts file.
 
Step 12
 
Now you have to create a table and use it for loop with the database name and take a variable name and then put all the field values. Now you have to run this project, after a few seconds, you can see that your application is run successfully. And now you have to fill in all the entries and press the post button. Now you can see that your data will be shown in the form of a table.
 
testdata.ts
  1. import{InMemoryDbService} from 'angular-in-memory-web-api'  
  2. export class TestData implements InMemoryDbService{  
  3.     createDb(){  
  4.   
  5.         let BookDetails=[  
  6.             {id:100, name:'JAVA ', Author:'C#corner',category:'Software devcelopment'},  
  7.             {id:101, name:'C Language', Author:'Tpoint',category:'test'},  
  8.             {id:102, name:'Web Technology', Author:'Google',category:' devcelopment'},  
  9.             {id:103, name:'Angular', Author:'C#corner',category:'Software devcelopment'}  
  10.              
  11.         ];  
  12.         return {  
  13.             books:BookDetails  
  14.         };  
  15.     }  
  16.   
  17. }  
Bookservice.ts 
  1. import { Injectable } from '@angular/core';  
  2. import {HttpClient, HttpHeaders} from '@angular/common/http';  
  3. import{Observable } from 'rxjs';  
  4. import { Book } from './book';  
  5. @Injectable({  
  6.   providedIn: 'root'  
  7. })  
  8. export class BookService {  
  9. bookUrl="api/books"  
  10.   
  11.   constructor( private http:HttpClient) { }  
  12.   
  13.   createbook(book:Book):Observable<Book>{  
  14.     let httpheaders=new HttpHeaders()  
  15.     .set('Content-type','application/Json');  
  16.     let options={  
  17.       headers:httpheaders  
  18.     };  
  19.     return this.http.post<Book>(this.bookUrl,book,options);  
  20.   }  
  21.   
  22.   getBooksFromStore():Observable<Book[]>{  
  23.     return this.http.get<Book[]>(this.bookUrl);  
  24.   }  
  25. }  
Adddata.ts 
  1. import { Component, OnInit } from '@angular/core';  
  2. import { FormGroup,FormBuilder,Validators } from '@angular/forms';  
  3. import { Observable } from 'rxjs';  
  4. import { Book } from '../book';  
  5. import { BookService } from '../book.service';  
  6.   
  7. @Component({  
  8.   selector: 'app-add',  
  9.   templateUrl: './add.component.html',  
  10.   styleUrls: ['./add.component.css']  
  11. })  
  12. export class AddComponent implements OnInit {  
  13. title='chaman gautam';  
  14. datasaved=false;  
  15. bookForm:FormGroup;  
  16. allbooks:Observable<Book[]>;  
  17.   
  18.   constructor(private formbuilder:FormBuilder, private bookservice:BookService) { }  
  19. ngOnInit(){  
  20.   this.bookForm=this.formbuilder.group({  
  21.     name:[' ',[Validators.required]],  
  22.     Author:[' ',[Validators.required]],  
  23.     catogery:[' ',[Validators.required]]  
  24.   
  25.   });  
  26.   this.getsoftBooks();  
  27. }  
  28. onFormSubmit(){  
  29.   this.datasaved=false;  
  30.   let book=this.bookForm.value;  
  31.   this.createbooks(book);  
  32.   this.bookForm.reset();  
  33. }  
  34. createbooks(book:Book){  
  35.   this.bookservice.createbook(book).subscribe(book=>{  
  36.     this.datasaved=true;  
  37.     this.getsoftBooks();  
  38.   
  39.   })  
  40. }  
  41.  getsoftBooks(){  
  42. this.allbooks=this.bookservice.getBooksFromStore();  
  43.  }  
  44.   
  45. }  
Adddata.html
  1. <h2>Hsttp client post methood call</h2>    
  2. <p *ngIf='datasaved' ngClass='success'>    
  3.     Record save successfully    
  4.     </p>    
  5.     <form [formGroup]='bookForm' (ngSubmit)='onFormSubmit()'>    
  6.         <table>    
  7.             <tr>    
  8.                 <td>ID:</td>    
  9.                 <td> <input formControlName="id"> </td>    
  10.             </tr>    
  11.             <tr>    
  12.                 <td>Name:</td>    
  13.                 <td> <input formControlName="name"> </td>    
  14.             </tr>    
  15.             <tr>    
  16.                 <td>Author:</td>    
  17.                 <td> <input formControlName="Author"> </td>    
  18.             </tr>    
  19.             <tr>    
  20.                 <td>Category:</td>    
  21.                 <td> <input formControlName="catogery"> </td>    
  22.             </tr>    
  23.             <tr>    
  24.                 <td colspan="2">      
  25.                     <button [disabled]="bookForm.invalid">Submit</button>    
  26.                 </td>    
  27.             </tr>    
  28.         </table>    
  29.         
  30.     </form>    
  31. <h2>View</h2>    
  32. <table border="2px">    
  33.     <tr>    
  34.         <td>Id</td>    
  35.         <td>Name</td>    
  36.         <td>Cetegory</td>    
  37.         <td>Author</td>    
  38.     </tr>    
  39.     <tr *ngFor='let bk of allbooks| async'>     
  40.     <td>{{bk.id}}</td>    
  41.     <td>{{bk.name}}</td>    
  42.     <td>{{bk.category}}</td>    
  43.     <td>{{bk.Author}}</td>    
  44. </tr>    
  45. </table>     
Module.ts
  1. import { NgModule } from '@angular/core';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3.   
  4. import { AppRoutingModule } from './app-routing.module';  
  5. import {HttpClientModule } from '@angular/common/http'  
  6. import { AppComponent } from './app.component';  
  7. import { AddComponent } from './add/add.component';  
  8. import { RouterModule, Routes} from '@angular/router';  
  9. import{BookService } from './book.service';  
  10. import {InMemoryWebApiModule } from 'angular-in-memory-web-api';  
  11. import {TestData } from './testdata'  
  12.   
  13. import { FormsModule, ReactiveFormsModule } from '@angular/forms';  
  14. import { ShowdataComponent } from './showdata/showdata.component';  
  15. import { CommonModule } from '@angular/common';  
  16. const routes: Routes = [  
  17.   {path:'', component:AddComponent},  
  18.   { path:'add', component:AddComponent}  
  19. ];  
  20.   
  21. @NgModule({  
  22.   declarations: [  
  23.     AppComponent,  
  24.     AddComponent,  
  25.     ShowdataComponent  
  26.   ],  
  27.   imports: [  
  28.     BrowserModule,  
  29.     AppRoutingModule,RouterModule.forRoot(routes),ReactiveFormsModule, FormsModule,  
  30.     HttpClientModule, CommonModule,  
  31.     InMemoryWebApiModule.forRoot(TestData)  
  32.   ],  
  33.   providers: [BookService],  
  34.   bootstrap: [AddComponent]  
  35. })  
  36. export class AppModule { }  
main.ts
  1. import { enableProdMode } from '@angular/core';  
  2. import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';  
  3.   
  4. import { AppModule } from './app/app.module';  
  5. import { environment } from './environments/environment';  
  6.   
  7. if (environment.production) {  
  8.   enableProdMode();  
  9. }  
  10.   
  11. platformBrowserDynamic().bootstrapModule(AppModule)  
  12.   .catch(err => console.error(err));  
Index.html
  1. <!doctype html>    
  2. <html lang="en">    
  3. <head>    
  4.   <meta charset="utf-8">    
  5.   <title>Dhwani</title>    
  6.   <base href="/">    
  7.   <meta name="viewport" content="width=device-width, initial-scale=1">    
  8.   <link rel="icon" type="image/x-icon" href="favicon.ico">    
  9. </head>    
  10. <body>    
  11.   <app-add></app-add>    
  12. </body>    
  13. </html>    
Now compile this application using the command " ng serve ".
 
After compiling successfully, you have to open the web browser and hit "localhost:4200" after a few seconds, your browser will be displayed output as,
 
OUTPUT 
 
 
Now you need to fill in the details after completion, the details form will be shown as,
 
 
You may now press the Submit button.
 
 
After pressing the Submit button, the result will appear as follows,
 
Now you can see that our data will be added and one message will be shown that "your data will be added successfully".
 
I hope you enjoy this article. Follow Chaman Gautam to learn more about Angular, and follow C# Corner to learn about more technology.