Add Data To The Server Using The Web API In Angular Using Node.js And VS Code

In this project, I'll walk you through how to store our data on the server and display it in the terminal.
 
First, you have to create a web API and an application. They must communicate with each other.
 
For storing data into the server, you have to follow the below steps,
 
Step 1 - First you have to create a WEB-API
 
First, you have to create a folder then open it in VS Code. Open the terminal and run the command npm init.
 
Fill in all the details and after complete this notification, you have to create a file where you have to create API and a query. To post the data you need to press the click button.
 
Click here to read how to create a web API.
 
Step 2
 
After creating a web API successfully, you have to create a web application/frontend for your web API.
 
Step 3
 
First, you have to create a folder in your system. Open this folder into the VS Code and run the command “ ng new demo” in the terminal. After creating the application successfully. You can open this application in VS Code.
 
Step 4
 
Now you have to create a service using the command “ ng g service user service.”
 
After creating service successfully, you can see that your service is registered in the module.ts file. That means you don’t need to register your service. Now go to the service.ts file and add your API URL’s and then create a query into the service.
 
Step 5
 
Now go to the .html file. In HTML file you have to take a div tag <div></div> and then take a form using the form tag<form></form>.
 
Then you have to create a function or a click event in the form tag. After creating a function on the form tag, you have to create text fields and label for entering the information like name, email, address, id, mobile, etc.
 
Step 6
 
Now you have to go to the .ts file and create an object of your service in the constructor. After creating a service object, import the service file with a proper path.
 
Now create a function that you created in the form tag. And then create a query for post-operation. Now check all dependencies and run this project.
 
Now you have to run your web API in another tab and check the output.
 
Example
  1. const express = require('express');  
  2. const bodyParser = require('body-parser');  
  3. const cors = require('cors');  
  4. const Port = 5000;  
  5. const app = express();  
  6. app.use(bodyParser.json());  
  7. app.use(cors());  
  8. app.get('/'function(req, res) {  
  9.     res.send('hello server 5000 is working ');  
  10. })  
  11. app.post('/enroll'function(req, res) {  
  12.     console.log(req.body);  
  13.     res.status(200).send({  
  14.         'messege''data recived'  
  15.     })  
  16. })  
  17. app.listen(Port, function() {  
  18.     console.log('server running on localhost: ' + Port)  
  19. });   
Then register this API web address in the service.
 
Service.ts
  1. import { Injectable } from '@angular/core';    
  2. import { HttpClient} from '@angular/common/http';    
  3. import { usermodel } from './usermodel';    
  4. import { Observable } from 'rxjs';    
  5. @Injectable({  
  6.     providedIn: 'root'  
  7. })  
  8. export class MyserviceService {  
  9.     url = 'http://localhost:5000/enroll'  
  10.     constructor(private httpclient: HttpClient) {}  
  11.     enroll(user: usermodel) {  
  12.         return this.httpclient.post < any > (this.url, user)  
  13.     }  
  14. }   
Submit.html
  1. <div class="header"><a id="linkcolor" [routerLink]="['/additem']">Add Item</a>      
  2.     <a id="linkcolor"  [routerLink]="['/search']">Search Item</a>      
  3.     <a id="linkcolor"  [routerLink]="['/todo']">todo</a>    
  4.     
  5.   </div>    
  6.     
  7. <br> <br>    
  8.   <div class="container">    
  9.     <h1>form submit data in angular</h1>    
  10.     <form #userForm="ngForm" (ngSubmit)="onSubmit()">    
  11.       <div class="form-group">    
  12.         <label>Name</label>    
  13.         <input type="text"  class="form-control"     
  14.         name="username" [(ngModel)]="objuser.name">    
  15.       </div><br>    
  16.       <div class="form-group">    
  17.         <label>Email</label>    
  18.         <input    
  19.         type="text"    
  20.         name="email"    
  21.         placeholder="Enter ToDo Text Here For Test....."    
  22.         class="todo-input"[(ngModel)]="objuser.email">    
  23.       </div><br>    
  24.       <div class="form-group">    
  25.         <label>Mobile</label>    
  26.         <input type="text"  class="form-control"     
  27.         name="usermobile" [(ngModel)]="objuser.mobile">    
  28.       </div> <br>    
  29.       <div class="form-group">    
  30.         <label>Address</label>    
  31.         <input type="text"  class="form-control"     
  32.         name="useraddress" [(ngModel)]="objuser.address">    
  33.       </div> <br>    
  34.     <button class="btn" type="submit" class="submit">Submit</button>    
  35. </form>    
Submit.ts
  1. import { Component, OnInit } from '@angular/core';    
  2. import { usermodel } from '../usermodel';    
  3. import {  MyserviceService} from '../myservice.service';    
  4. @Component({  
  5.     selector: 'app-register',  
  6.     templateUrl: './register.component.html',  
  7.     styleUrls: ['./register.component.css']  
  8. })  
  9. export class RegisterComponent implements OnInit {  
  10.     objuser: usermodel = new usermodel();  
  11.     constructor(private MyserviceService: MyserviceService) {}  
  12.     ngOnInit(): void {}  
  13.     onSubmit() {  
  14.         this.MyserviceService.enroll(this.objuser).subscribe(data => console.log('success', data), error => console.log('error', error))  
  15.     }  
  16. }   
.css
  1. .header{  
  2.     margin0;  
  3.     padding0;  
  4.     width100%;  
  5.     height50px;  
  6.     background-color: cyan;  
  7.     colorwhite;  
  8.       
  9.     }  
  10.     .a{  
  11.         colorwhite;   
  12.         text-decorationnone;  
  13.         font-size20px;  
  14.         font-familysans-serif;  
  15.         font-weight700;  
  16.     }  
  17.     a:link{  
  18.         text-decorationnone;  
  19.         colorwhite;  
  20.     }  
  21.       
  22.     .formset{  
  23.   
  24. text-aligncenter;  
  25.   
  26.     }  
  27.     .input{  
  28.         background-colorgray;  
  29.     }  
Module.ts
  1. import { NgModule } from '@angular/core';  
  2. import { FormsModule } from '@angular/forms';  
  3. import { BrowserModule } from '@angular/platform-browser';  
  4.   
  5. import { AppRoutingModule } from './app-routing.module';  
  6. import { AppComponent } from './app.component';  
  7. import { TodoComponent } from './Todo/todo.component';  
  8. import { RegisterComponent } from './register/register.component';  
  9. import { SearchComponent } from './search/search.component';  
  10. import { RouterModule, Routes} from '@angular/router';  
  11. import{ HttpClientModule} from '@angular/common/http'  
  12. const routes: Routes = [  
  13.   
  14.   {path:'', component:TodoComponent},  
  15.   { path:'additem', component:RegisterComponent},  
  16.   {path:'search', component:SearchComponent},  
  17.   { path: '**', component:TodoComponent}  
  18. ];  
  19. @NgModule({  
  20.   declarations: [  
  21.     AppComponent,  
  22.     TodoComponent,  
  23.     RegisterComponent,  
  24.     SearchComponent  
  25.   ],  
  26.   imports: [  
  27.     BrowserModule,  
  28.     AppRoutingModule,FormsModule, RouterModule.forRoot(routes),HttpClientModule  
  29.   ],  
  30.   providers: [],  
  31.   bootstrap: [AppComponent]  
  32. })  
  33. export class AppModule { }  
mains.ts
  1. import { enableProdMode } from '@angular/core';    
  2. import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';    
  3. import { AppModule } from './app/app.module';    
  4. import { environment } from './environments/environment';    
  5. if (environment.production) {  
  6.     enableProdMode();  
  7. }  
  8. platformBrowserDynamic().bootstrapModule(AppModule).catch(err => console.error(err));   
Index.html
  1. <!doctype html>    
  2. <html lang="en">    
  3. <head>    
  4.   <meta charset="utf-8">    
  5.      <title>Todo</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-root></app-root>    
  12.    </body>    
  13. </html>     
Now you have to run this web API using the command " node post.js".
 
Open the browser, type " localhost:5000" and press the enter button.
 
After running the web API you have to compile this application using the command " ng serve". After compiling successfully you have to open the browser and hit "localhost:4200".
 
After running the project your browser shows the output like,
 
OUTPUT
 
Add Data To The Server Using The Web API In Angular Using Node.js And VS Code
 
Add Data To The Server Using The Web API In Angular Using Node.js And VS Code
 
Now we have to fill in the details two times and press the submit button. Now we have to go to the terminal and check that our data is showing or not. 
 
The terminal output will be shown like,
 
Add Data To The Server Using The Web API In Angular Using Node.js And VS Code
 
Now you can see that our data will be shown in the terminal. that means our application and API is working properly. 
 
Follow me Chaman Gautam to learn more about angular. follow  C# Corner to learn about more technology.


Similar Articles