How To Use Behavior Subject In Angular 10

Introduction

 
In this article, we will learn how to use Behavior Subject in Angular 10. Behavior Subject is a part of the RxJs library and is used for cross component communications. We can send data from one component to other components using Behavior Subject. In Behavior Subject we can set the initial value .
 
Prerequisites
  • Basic Knowledge of Angular 2 or higher
  • Visual Studio Code
  • Visual studio and SQL Server Management studio
  • Node and NPM installed
  • Bootstrap
Create an Angular project by using the following command.
  1. ng new SubjectbehaviourDemo  
Open this project in Visual Studio Code and install Bootstrap by using following command.
  1. npm install bootstrap --save   
Now open styles.css file and add Bootstrap file reference. To add reference in styles.css file add this line.
  1. @import '~bootstrap/dist/css/bootstrap.min.css';  
Now create a folder named 'Layout' and inside it create three components. In this demo we send data from home component to leftsidebar component.
  1. Home
  2. Header
  3. Leftsidebar 
    1. ng g c Home    
    2. ng g c Header       
    3. ng g c Leftsidebar   
Now create a service to call the Web API by using the following command.
  1. ng g s ShareDataService    
Now open share-data.service.ts file and add the following lines,
  1. import { Injectable } from '@angular/core';    
  2. import { HttpClient } from "@angular/common/http";    
  3. import { BehaviorSubject } from 'rxjs';    
  4. @Injectable({    
  5.   providedIn: 'root'    
  6. })    
  7. export class ShareDataService {    
  8.   name: any;    
  9.   public content = new BehaviorSubject<any>(this.name);    
  10.   public share = this.content.asObservable();    
  11.   public Employeename = [];    
  12.   constructor(private http: HttpClient) { }    
  13.   getLatestValue(data) {    
  14.     debugger;    
  15.     this.content.next(data);    
  16.     this.Employeename = data;    
  17.     console.log(this.Employeename);    
  18.   }    
  19.   Saveuser(data) {    
  20.     debugger;    
  21.     return this.http.post('http://localhost:1680/api/employee/InsertEmployee', data)    
  22.   }    
  23.   getdetails() {    
  24.     debugger;    
  25.     return this.http.get('http://localhost:1680/api/employee/Getdetaisl')    
  26.   }    
  27.     
  28. }  
 Now open left-sidebar.component.ts file and add the following code,
  1. import { Component, OnInit } from '@angular/core';    
  2. import { ShareDataService } from "../../share-data.service";    
  3. @Component({    
  4.   selector: 'app-left-sidebar',    
  5.   templateUrl: './left-sidebar.component.html',    
  6.   styleUrls: ['./left-sidebar.component.css']    
  7. })    
  8. export class LeftSidebarComponent implements OnInit {    
  9. name:any;    
  10. employeenameLatest: any;    
  11. playListDetails:any;    
  12.   constructor(public shareDataService:ShareDataService) { }    
  13.   ngOnInit(): void {    
  14.     this.shareDataService.share.subscribe(x =>    
  15.       this.employeenameLatest = x)    
  16.       this.employeenameLatest = this.employeenameLatest;    
  17.       console.log(this.employeenameLatest);    
  18.     this.shareDataService.getdetails().subscribe((data: any) => {    
  19.       this.name = data;    
  20.       console.log(this.name);    
  21.       this.shareDataService.Employeename = this.name;    
  22.     })    
  23.   }    
  24. }   
Now open left-sidebar.component.html file and add the following code,
  1. <ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar">    
  2.     
  3.     <!-- Sidebar - Brand -->    
  4.     <a class="sidebar-brand d-flex align-items-center justify-content-center" href="index.html">    
  5.       <div class="sidebar-brand-icon rotate-n-15">    
  6.         <i class="fas fa-laugh-wink"></i>    
  7.       </div>    
  8.     </a>    
  9.     
  10.     <!-- Divider -->    
  11.     <hr class="sidebar-divider my-0">    
  12.     <!-- Divider -->    
  13.     <hr class="sidebar-divider">    
  14.     <!-- Nav Item - Pages Collapse Menu -->    
  15.     <li class="nav-item">    
  16.       <a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="true" aria-controls="collapseTwo">    
  17.         <i class="fas fa-fw fa-cog"></i>    
  18.         <span>Employee Name</span>    
  19.       </a>    
  20.       <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionSidebar">    
  21.         <div class="bg-white py-2 collapse-inner rounded" *ngFor="let content of shareDataService.Employeename">    
  22.           <h6 class="collapse-header">{{content.EmployeeName}}</h6>    
  23.         </div>    
  24.       </div>    
  25.     </li>    
  26.   </ul>    
Now open home.component.ts file and add the following code,
  1. import { Component, OnInit } from '@angular/core';    
  2. import { ShareDataService } from "../../share-data.service";    
  3. @Component({    
  4.   selector: 'app-home',    
  5.   templateUrl: './home.component.html',    
  6.   styleUrls: ['./home.component.css']    
  7. })    
  8. export class HomeComponent implements OnInit {    
  9.   users = new Users();    
  10.   empDetails: any;    
  11.   constructor(private shareDataService: ShareDataService) { }    
  12.   data: any;    
  13.   ngOnInit(): void {    
  14.   }    
  15.   showname() {    
  16.     this.shareDataService.getdetails().subscribe((data: any) => {    
  17.       this.empDetails = data;    
  18.       debugger;    
  19.       this.shareDataService.getLatestValue(this.empDetails);    
  20.     })    
  21.   }    
  22.   saveuser() {    
  23.     debugger;    
  24.     this.shareDataService.Saveuser(this.users).subscribe(res => {    
  25.       this.showname();    
  26.     })    
  27.     
  28.   }    
  29. }    
  30. class Users {    
  31.   EmployeeName: any;    
  32.   city: any;    
  33.   email: any;    
  34.   password: any;    
  35.   department: any;    
  36. }    
 Now open home.component.html file and add the following code,
  1. <div class="container">    
  2.     
  3.     <div class="card o-hidden border-0 shadow-lg my-5">    
  4.       <div class="card-body p-0">    
  5.         <div class="row">    
  6.           <div class="col-lg-12">    
  7.             <div class="p-5">    
  8.               <div class="text-center">    
  9.                 <h1 class="h4 text-gray-900 mb-4">Create an Account!</h1>    
  10.               </div>    
  11.               <form class="user" (ngSubmit)="saveuser()">    
  12.                 <div class="form-group row">    
  13.                   <div class="col-sm-6 mb-3 mb-sm-0">    
  14.                     <input type="text" class="form-control form-control-user" style="border-radius: 0rem !important" [(ngModel)]="users.EmployeeName" id="name" name="EmployeeName" placeholder="Name">    
  15.                   </div>    
  16.                   <div class="col-sm-6">    
  17.                     <input type="text" class="form-control form-control-user" style="border-radius: 0rem !important" id="exampleLastName" [(ngModel)]="users.city" name="city" placeholder="City">    
  18.                   </div>    
  19.                 </div>    
  20.                 <div class="form-group">    
  21.                   <input type="text" class="form-control form-control-user" style="border-radius: 0rem !important" id="exampleInputEmail" [(ngModel)]="users.email" name="email"  placeholder="Email Address">    
  22.                 </div>    
  23.                 <div class="form-group row">    
  24.                   <div class="col-sm-6 mb-3 mb-sm-0">    
  25.                     <input type="text" class="form-control form-control-user" style="border-radius: 0rem !important" id="exampleInputPassword" [(ngModel)]="users.password" name="password" placeholder="Password">    
  26.                   </div>    
  27.                   <div class="col-sm-6 mb-3 mb-sm-0">    
  28.                     <input type="text" class="form-control form-control-user" style="border-radius: 0rem !important" id="exampleInputPassword" [(ngModel)]="users.department"  name="department"  placeholder="Department">    
  29.                   </div>    
  30.                      
  31.                 </div>    
  32.                 <input type="submit" value=" Register Account" style="border-radius: 0rem !important" class="btn btn-primary btn-user btn-block"/>    
  33.                   Register Account    
  34.                 <!-- </button> -->    
  35.                 <hr>    
  36.                    
  37.               </form>    
  38.               <hr>    
  39.             </div>    
  40.           </div>    
  41.         </div>    
  42.       </div>    
  43.     </div>    
  44.     
  45.   </div>    
 Now open app.component.html file and add the following code.
  1. <div id="wrapper">    
  2.   <app-left-sidebar></app-left-sidebar>    
  3.   <div id="content-wrapper" class="d-flex flex-column">    
  4.     <div id="content">    
  5.       <app-header></app-header>    
  6.       <app-home></app-home>    
  7.     </div>    
  8.   </div>    
  9. </div>   
Now open app.module.ts file and add the following code.
  1. import { BrowserModule } from '@angular/platform-browser';    
  2. import { NgModule } from '@angular/core';    
  3. import { HeaderComponent } from "./layout/header/header.component";    
  4. import { LeftSidebarComponent } from "./layout/left-sidebar/left-sidebar.component";    
  5. import { HomeComponent } from "./layout/home/home.component";    
  6. import { AppComponent } from './app.component';    
  7. import { FormsModule } from '@angular/forms';    
  8. import { HttpClientModule } from "@angular/common/http";    
  9. @NgModule({    
  10.   declarations: [    
  11.     AppComponent,HomeComponent,LeftSidebarComponent,HeaderComponent    
  12.   ],    
  13.   imports: [    
  14.     BrowserModule,FormsModule,HttpClientModule    
  15.   ],    
  16.   providers: [],    
  17.   bootstrap: [AppComponent]    
  18. })    
  19. export class AppModule { }    

Create a database and table

 
Open SQL Server Management Studio, create a database named Employees and in this database, create a table. Give that table a name like EmployeeLogin
  1. CREATE TABLE [dbo].[EmployeeLogin](          
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,          
  3.     [Email] [varchar](50) NULL,          
  4.     [Password] [varchar](50) NULL,          
  5.     [EmployeeName] [varchar](50) NULL,          
  6.     [City] [varchar](50) NULL,          
  7.     [Department] [varchar](50) NULL,          
  8.  CONSTRAINT [PK_EmployeeLogin] PRIMARY KEY CLUSTERED           
  9. (          
  10.     [Id] ASC          
  11. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]          
  12. ON [PRIMARY]          
  13.           
  14. GO      

Create a Web API Project

 
Open Visual Studio and create a new project.
 
 
Change the name as LoginwithreactHooks and Click ok  
 
Select Web API as its template.
 
 
 Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.
 
 
Click on the "ADO.NET Entity Data Model" option and click "Add".
 
 
Select EF Designer from the database and click the "Next" button. 
 
 
Add the connection properties and select database name on the next page and click OK.  
 
 
Check the Table checkbox. The internal options will be selected by default. Now, click the "Finish" button.
 
 
 
Our data model is successfully created now. 
 
Now, Right-click on the Models folder and add two classes Register, and Response respectively. Now, paste the following codes in these classes.  
 
Register Class
  1. public class Register        
  2.   {        
  3.       public int Id { getset; }        
  4.       public string Email { getset; }        
  5.       public string Password { getset; }        
  6.       public string EmployeeName { getset; }        
  7.       public string City { getset; }        
  8.       public string Department { getset; }        
  9.   }  
 Response Class
  1. public class Response        
  2.    {        
  3.        public string Status { setget; }        
  4.        public string Message { setget; }        
  5.         
  6.    }   
Right-click on the Controllers folder and add a new controller. Name it as "Employee controller" and add the following namespace.
  1. using LoginWithReacthooks.Models;    
Create two methods in this controller to insert and getdetails and add the following code in this controller. 
  1. using System;      
  2. using System.Collections.Generic;      
  3. using System.Linq;      
  4. using System.Net;      
  5. using System.Net.Http;      
  6. using System.Web.Http;      
  7. using LoginWithReacthooks.Models;      
  8. namespace LoginWithReacthooks.Controllers      
  9. {      
  10.     public class employeeController : ApiController      
  11.     {      
  12.         RestaurantsEntities DB = new RestaurantsEntities();      
  13.         [Route("InsertEmployee")]      
  14.         [HttpPost]      
  15.         public object InsertEmployee(Register Reg)      
  16.         {      
  17.             try      
  18.             {      
  19.                 EmployeeLogin EL = new EmployeeLogin();      
  20.                      
  21.                     EL.EmployeeName = Reg.EmployeeName;      
  22.                     EL.City = Reg.City;      
  23.                     EL.Email = Reg.Email;      
  24.                     EL.Password = Reg.Password;      
  25.                     EL.Department = Reg.Department;      
  26.                     DB.EmployeeLogins.Add(EL);      
  27.                     DB.SaveChanges();      
  28.                     return new Response      
  29.                     { Status = "Success", Message = "Record SuccessFully Saved." };      
  30.                       
  31.             }      
  32.             catch (Exception)      
  33.             {      
  34.       
  35.                 throw;      
  36.             }      
  37.                 
  38.         }      
  39.       
  40.         [Route("Getdetaisl")]      
  41.         [HttpPost]      
  42.         public object Getdetaisl()      
  43.         {      
  44.             return DB.EmployeeLogins.ToList();      
  45.         }      
  46.     }      
  47. }   
Now, let's enable CORS. Go to Tools, open NuGet Package Manager, search for CORS, and install the "Microsoft.Asp.Net.WebApi.Cors" package. Open Webapiconfig.cs and add the following lines,
  1. EnableCorsAttribute cors = new EnableCorsAttribute("*""*""*");          
  2. config.EnableCors(cors);   
Now go to vs code and run the project using the following command 'npm start'.
 
Enter values in the textboxes and click on the button. 
 

Summary

 
In this article, we learned how to use Behavior Subject in Angular 10 applications.


Similar Articles