Post Operation With Angular Using Dummy API

How to complete the login operation in Angular

 
First, you have to create an application in angular using the " ng new demo" command.  After successfully creating the application you have to create a separate module for your application using the command "ng g module". 
  • then create a component using the command " ng g component demo" 
  • then create a wrapper class. 
  • then create a service using the command " ng g service". 
  • then create a brought file using the command "ng g component". 
Now go to the module.ts file and write the code
  1. import {NgModule } from '@angular/core';    
  2. import { logincomponent } from './login.component';    
  3. import { BrowserModule } from '@angular/platform-browser';    
  4. import { FormsModule} from '@angular/forms';    
  5. import { userservice } from '../service/userservice';    
  6. import { HttpClientModule} from '@angular/common/http' ;    
  7. import{ RouterModule } from "@angular/router";    
  8. import { routes } from '../loginmodule/login.rout';    
  9. import { welcomeComponent } from '../welcome/welcome.Component';    
  10. import { homecomponent } from '../home/home.component';    
  11. import { ReactiveComponent } from '../reactive/reactive.component';    
  12. import { ReactiveFormsModule} from '@angular/forms'    
  13. @NgModule({  
  14.     declarations: [logincomponent, welcomeComponent, homecomponent, ReactiveComponent],  
  15.     imports: [BrowserModule, FormsModule, HttpClientModule, ReactiveFormsModule, RouterModule.forRoot(routes)],  
  16.     providers: [userservice],  
  17.     bootstrap: [homecomponent]  
  18. })  
  19. export class loginmodule {}  
In this module, the user registered all the component services and modules. 
 
Now go to the services and write code 
  1. import {Injectable} from '@angular/core';    
  2. import{HttpClient} from '@angular/common/http';    
  3. @Injectable()  
  4. export class userservice {  
  5.     constructor(private http: HttpClient) {}  
  6.     loginuser(obj) {  
  7.         return this.http.post("   API ", obj);  
  8.     }  
  9. }  
In the service component, the user creates a login object and adds an API where the right API. then goes to the route's component.
 
In the route's component write the code
  1. import{Routes } from "@angular/router";    
  2. import { logincomponent } from '../loging/login.component';    
  3. import { welcomeComponent } from '../welcome/welcome.Component';    
  4. import { ReactiveComponent } from '../reactive/reactive.component';    
  5. export const routes: Routes = [{  
  6.     path: '',  
  7.     component: logincomponent  
  8. }, {  
  9.     path: 'movies/:email ',  
  10.     component: ReactiveComponent  
  11. }, {  
  12.     path: 'loging',  
  13.     component: logincomponent  
  14. }, {  
  15.     path: 'reactive',  
  16.     component: ReactiveComponent  
  17. }, {  
  18.     path: '**',  
  19.     component: logincomponent  
  20. }]   
In the routes file section user creates the path of the application where the user wants to render your application after logging in or which part it displays first.
 
Now go to the wrapper class and write the code. 
  1. export class Usermodel{    
  2.     public email: string;    
  3.     public password: number;    
  4. }     
In the wrapper class user take the username and password in a class that the class object creates in the login.ts component. 
 
Go to the HTML component and write the code 
 
login.html
  1. <form (ngSubmit)="loginUser()">  
  2.     <input [(ngModel)]="objUser.email"  type="email"  name="email" placeholder="Your first name" required  ngModel>  
  3.        <br>  
  4.         <br>  
  5.          <input [(ngModel)]="objUser.password"  type="password" class="password"  name="password" placeholder="Your first password" required  ngModel>  
  6.        <br>  
  7.      <br>  
  8.     <input type="submit" name="submit" class="submit"  value="login" >  
  9. </form>    
In the HTML component the user creates a form and a function in the form. which function is created in the service class. 
 
Go to the ts component and write the code 
  1. import { Component } from '@angular/core';    
  2. import { Usermodel } from '../model/Usermodel';    
  3. import { userservice } from '../service/userservice';    
  4. import{Router } from '@angular/router';   
  5. @Component({  
  6.     selector: ' login',  
  7.     templateUrl: './login.component.html',  
  8.     styleUrls: ['./login.component.css']  
  9. })  
  10. export class logincomponent {  
  11.     title = "chaman";  
  12.     localsdata = "";  
  13.     sessionsdata = " ";  
  14.     objUser: Usermodel = new Usermodel();  
  15.     constructor(private userservice: userservice, private route: Router) {  
  16.         this.localsdata = localStorage.getItem('localskey');  
  17.         this.sessionsdata = sessionStorage.getItem('sessionkey');  
  18.     }  
  19.     loginUser(objUser) {  
  20.             this.userservice.loginuser(this.objUser).subscribe(x => {  
  21.                 if (x != undefined && x != null && x != '') {  
  22.                     //this.route.navigate(['./reactive'],{ queryParams: {name:'Chaman Gautam'} });    
  23.                     //   this.route.navigate(['./welcome',{ name:'chaman'}]);    
  24.                     this.route.navigate(['./reactive']);  
  25.                 } else {  
  26.                     alert('fail');  
  27.                 }  
  28.             })  
In this code user has created an object of wrapper class and registered a service and routes into the constructor. Then create an object and then create a query in this object, and then set the path using navigate. and add an alert box into the object that if you have entered the correct email or password then login successfully otherwise alert shows that your user id and password are incorrect.  
 
Now go to the .css class to make your form attractive. 
 
Now go to the .css file and write code.
 
login.css
  1. .form-control{  
  2.     text-aligncenter;  
  3.     width200px;  
  4.     height40px;  
  5.     colorblack;  
  6.     border-colorblack;  
  7.     background-color: cornsilk;  
  8.     border-radius: 1px;  
  9.     border-style0.5px;  
  10. }  
  11. .btn-btn-primary{        
  12.     text-aligncenter;        
  13.     border-radius: 6px;        
  14.     background-color#1976d2;        
  15.     width80px;        
  16.     height:30px;        
  17.     border-stylehidden;        
  18.     colorwhite;      
  19. }  
  20. input.ng-invalid.ng-touched{  
  21.     border-colorred;   
  22. }  
  23. .text{  
  24.     text-aligncenter;  
  25.     font-sizex-large;  
  26. }  
  27. .container{  
  28.     text-aligncenter;  
  29. }  
Now create another component using the command " ng g component reactive", where the user renders after logging in successfully. 
 
Now go to the HTML page and write code.
 
reactive.html
  1. <h1 class="text">Welcome to {{title}}</h1>  
  2. <div class="container">  
  3.     <div class="row">  
  4.         <div class="form-bg">  
  5.             <form [formGroup]='signupForm' (ngSubmit)='PostData(signupForm)'>  
  6.                 <div class="form-group">  
  7.                     <input type="text" class="form-control" formControlName='fname' placeholder="Your first name" >  
  8.                     </div>  
  9.                     <br>  
  10.                         <div class="form-group" >  
  11.                             <input type="text" class="form-control" formControlName="lname" placeholder="enter lastname" >  
  12.                          </div>  
  13.                          <br>  
  14.                          <div class="form-group">  
  15.                              <input type="age" class="form-control" formControlName="age" placeholder="Enter Your age" >  
  16.                          </div>  
  17.                         <br>  
  18.                        <div class="form-group">  
  19.                            <input type="mobile" class="form-control" formControlName="mobile" placeholder="Enter your mobile">  
  20.                        </div>  
  21.                     <br>  
  22.                   <div class="form-group">  
  23.                       <input type="address" class="form-control" formControlName="address" placeholder="Enter your address">  
  24.                   </div>  
  25.                 <br>  
  26.                <be>  
  27.               <div>  
  28.                 <input type="submit" class="btn-primary" value="PostData" [disabled]='!signupForm.valid'>  
  29.              </div>  
  30.           </form>  
  31.        </div>  
  32.    </div>  
  33. </div>    
Now go to the .css file to make more your page more attractive.
 
reactive.css
  1. .form - control {  
  2.         text - align: center;  
  3.         width200 px;  
  4.         height40 px;  
  5.         colorblack;  
  6.         border - colorblack;  
  7.         background - color: cornsilk;  
  8.         border - radius: 1 px;  
  9.         border - style: 0.5 px;  
  10.     }.btn - primary {  
  11.         text - align: center;  
  12.         border - radius: 6 px;  
  13.         background - color#1976d2;    
  14.     width80px;    
  15.     height:30px;    
  16.     border-stylehidden;    
  17.     colorwhite;    
  18. }    
  19. input.ng-invalid.ng-touched{    
  20.     border-colorred;     
  21. }    
  22. .text{    
  23.     text-aligncenter;    
  24.     font-sizex-large;    
  25. }    
  26. .container{    
  27.     text-aligncenter;    
  28. }     
Now go to the reactive. component and write the code
 
reactive.ts
  1. import {  
  2.     Component,  
  3.     OnInit  
  4. } from '@angular/core';  
  5. import {  
  6.     FormControl,  
  7.     FormGroup,  
  8.     FormBuilder,  
  9.     NgForm,  
  10.     Validator,  
  11.     Validators  
  12. } from '@angular/forms'  
  13. @Component({  
  14.     selector: 'app-reactive',  
  15.     templateUrl: './reactive.component.html',  
  16.     styleUrls: ['./reactive.component.css']  
  17. })  
  18. export class ReactiveComponent {  
  19.     title = 'reactive form ';  
  20.     signup form: FormGroup;  
  21.     FirstName: string = "";  
  22.     LastName: string = "";  
  23.     age: string = "";  
  24.     address: string = "";  
  25.     Mobile: String = "";  
  26.     constructor(private frmbuilder: FormBuilder) {  
  27.         this.signupForm = frmbuilder.group({  
  28.             /*fname:new FormControl(),                  
  29.                lname:new FormControl(),  
  30.               email:new FormControl(),      
  31.               password:new FormControl()*/  
  32.             fname: ['', [Validators.required, Validators.minLength(1)]],  
  33.             lname: ['', [Validators.required, Validators.minLength(1)]],  
  34.             age: ['', [Validators.required, Validators.minLength(2)]],  
  35.             mobile: ['', [Validators.required, Validators.minLength(10)]],  
  36.             address: ['', [Validators.required, Validators.maxLength(100)]]  
  37.         });  
  38.     }  
  39.     PostData(signupForm: any) {  
  40.         this.FirstName = signupForm.controls.fname.value;  
  41.         this.LastName = signupForm.controls.lname.value;  
  42.         this.age = signupForm.controls.age.value;  
  43.         this.Mobile = signupForm.controls.mobile.value;  
  44.         this.address = signupForm.controls.address.value;  
  45.         console.log(this.FirstName);  
  46.         console.log(this.LastName);  
  47.         console.log(this.age);  
  48.         console.log(this.address);  
  49.         console.log(this.Mobile);  
  50.         console.log(signupForm.controls);  
  51.     }  
  52. }   
Now go to the main.ts file and register your module 
 
main.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. import { loginmodule } from './app/loging/login.module';    
  6. import { homemodule } from './app/home/home.module';    
  7. if (environment.production) {    
  8.   enableProdMode();    
  9. }    
  10. platformBrowserDynamic().bootstrapModule(loginmodule)    
  11.   .catch(err => console.error(err));     
Now go to the index.html page for registering  your selected name which you display first
 
index.html
  1. <!doctype html>    
  2. <html lang="en">    
  3. <head>    
  4.   <meta charset="utf-8">    
  5.   <title>Login</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.   <home></home>    
  12. </body>    
  13. </html>     
Now compile this project using the command " ng serve" when the project compiles successfully, then you have to go to the browser and hit in the browser " localhost:4200" after a few seconds you can see the output like this. 
 
OUTPUT
 
 
Now fill in the valid id and password.
 
After filling g the valid id and password
 
 
Now click on the login button. After clicking the login button the output will be shown like this.
 
 
Now you can see that we have successfully login with a valid username and password.
 
I hope you enjoy this article. To learn more about angular follow me on C#Corner Chaman Gautam; to learn about more technology follow C#Corner.  


Similar Articles