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
- import{InMemoryDbService} from 'angular-in-memory-web-api'
- export class TestData implements InMemoryDbService{
- createDb(){
-
- let BookDetails=[
- {id:100, name:'JAVA ', Author:'C#corner',category:'Software devcelopment'},
- {id:101, name:'C Language', Author:'Tpoint',category:'test'},
- {id:102, name:'Web Technology', Author:'Google',category:' devcelopment'},
- {id:103, name:'Angular', Author:'C#corner',category:'Software devcelopment'}
-
- ];
- return {
- books:BookDetails
- };
- }
-
- }
Bookservice.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) { }
-
- 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);
- }
-
- getBooksFromStore():Observable<Book[]>{
- return this.http.get<Book[]>(this.bookUrl);
- }
- }
Adddata.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[]>;
-
- constructor(private formbuilder:FormBuilder, private bookservice:BookService) { }
- ngOnInit(){
- this.bookForm=this.formbuilder.group({
- name:[' ',[Validators.required]],
- Author:[' ',[Validators.required]],
- catogery:[' ',[Validators.required]]
-
- });
- this.getsoftBooks();
- }
- onFormSubmit(){
- this.datasaved=false;
- let book=this.bookForm.value;
- this.createbooks(book);
- this.bookForm.reset();
- }
- createbooks(book:Book){
- this.bookservice.createbook(book).subscribe(book=>{
- this.datasaved=true;
- this.getsoftBooks();
-
- })
- }
- getsoftBooks(){
- this.allbooks=this.bookservice.getBooksFromStore();
- }
-
- }
Adddata.html
- <h2>Hsttp client post methood call</h2>
- <p *ngIf='datasaved' ngClass='success'>
- Record save successfully
- </p>
- <form [formGroup]='bookForm' (ngSubmit)='onFormSubmit()'>
- <table>
- <tr>
- <td>ID:</td>
- <td> <input formControlName="id"> </td>
- </tr>
- <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="catogery"> </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>
- </tr>
- <tr *ngFor='let bk of allbooks| async'>
- <td>{{bk.id}}</td>
- <td>{{bk.name}}</td>
- <td>{{bk.category}}</td>
- <td>{{bk.Author}}</td>
- </tr>
- </table>
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';
- const routes: Routes = [
- {path:'', component:AddComponent},
- { path:'add', component:AddComponent}
- ];
-
- @NgModule({
- declarations: [
- AppComponent,
- AddComponent,
- ShowdataComponent
- ],
- 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
- <!doctype html>
- <html lang="en">
- <head>
- <meta charset="utf-8">
- <title>Dhwani</title>
- <base href="/">
- <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 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.