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.
- ng new SubjectbehaviourDemo
Open this project in Visual Studio Code and install Bootstrap by using following command.
- npm install bootstrap --save
Now open styles.css file and add Bootstrap file reference. To add reference in styles.css file add this line.
- @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.
-
-
-
Leftsidebar
- ng g c Home
- ng g c Header
- ng g c Leftsidebar
Now create a service to call the Web API by using the following command.
Now open share-data.service.ts file and add the following lines,
- import { Injectable } from '@angular/core';
- import { HttpClient } from "@angular/common/http";
- import { BehaviorSubject } from 'rxjs';
- @Injectable({
- providedIn: 'root'
- })
- export class ShareDataService {
- name: any;
- public content = new BehaviorSubject<any>(this.name);
- public share = this.content.asObservable();
- public Employeename = [];
- constructor(private http: HttpClient) { }
- getLatestValue(data) {
- debugger;
- this.content.next(data);
- this.Employeename = data;
- console.log(this.Employeename);
- }
- Saveuser(data) {
- debugger;
- return this.http.post('http://localhost:1680/api/employee/InsertEmployee', data)
- }
- getdetails() {
- debugger;
- return this.http.get('http://localhost:1680/api/employee/Getdetaisl')
- }
-
- }
Now open left-sidebar.component.ts file and add the following code,
- import { Component, OnInit } from '@angular/core';
- import { ShareDataService } from "../../share-data.service";
- @Component({
- selector: 'app-left-sidebar',
- templateUrl: './left-sidebar.component.html',
- styleUrls: ['./left-sidebar.component.css']
- })
- export class LeftSidebarComponent implements OnInit {
- name:any;
- employeenameLatest: any;
- playListDetails:any;
- constructor(public shareDataService:ShareDataService) { }
- ngOnInit(): void {
- this.shareDataService.share.subscribe(x =>
- this.employeenameLatest = x)
- this.employeenameLatest = this.employeenameLatest;
- console.log(this.employeenameLatest);
- this.shareDataService.getdetails().subscribe((data: any) => {
- this.name = data;
- console.log(this.name);
- this.shareDataService.Employeename = this.name;
- })
- }
- }
Now open left-sidebar.component.html file and add the following code,
- <ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar">
-
- <!-- Sidebar - Brand -->
- <a class="sidebar-brand d-flex align-items-center justify-content-center" href="index.html">
- <div class="sidebar-brand-icon rotate-n-15">
- <i class="fas fa-laugh-wink"></i>
- </div>
- </a>
-
- <!-- Divider -->
- <hr class="sidebar-divider my-0">
- <!-- Divider -->
- <hr class="sidebar-divider">
- <!-- Nav Item - Pages Collapse Menu -->
- <li class="nav-item">
- <a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="true" aria-controls="collapseTwo">
- <i class="fas fa-fw fa-cog"></i>
- <span>Employee Name</span>
- </a>
- <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionSidebar">
- <div class="bg-white py-2 collapse-inner rounded" *ngFor="let content of shareDataService.Employeename">
- <h6 class="collapse-header">{{content.EmployeeName}}</h6>
- </div>
- </div>
- </li>
- </ul>
Now open home.component.ts file and add the following code,
- import { Component, OnInit } from '@angular/core';
- import { ShareDataService } from "../../share-data.service";
- @Component({
- selector: 'app-home',
- templateUrl: './home.component.html',
- styleUrls: ['./home.component.css']
- })
- export class HomeComponent implements OnInit {
- users = new Users();
- empDetails: any;
- constructor(private shareDataService: ShareDataService) { }
- data: any;
- ngOnInit(): void {
- }
- showname() {
- this.shareDataService.getdetails().subscribe((data: any) => {
- this.empDetails = data;
- debugger;
- this.shareDataService.getLatestValue(this.empDetails);
- })
- }
- saveuser() {
- debugger;
- this.shareDataService.Saveuser(this.users).subscribe(res => {
- this.showname();
- })
-
- }
- }
- class Users {
- EmployeeName: any;
- city: any;
- email: any;
- password: any;
- department: any;
- }
Now open home.component.html file and add the following code,
- <div class="container">
-
- <div class="card o-hidden border-0 shadow-lg my-5">
- <div class="card-body p-0">
- <div class="row">
- <div class="col-lg-12">
- <div class="p-5">
- <div class="text-center">
- <h1 class="h4 text-gray-900 mb-4">Create an Account!</h1>
- </div>
- <form class="user" (ngSubmit)="saveuser()">
- <div class="form-group row">
- <div class="col-sm-6 mb-3 mb-sm-0">
- <input type="text" class="form-control form-control-user" style="border-radius: 0rem !important" [(ngModel)]="users.EmployeeName" id="name" name="EmployeeName" placeholder="Name">
- </div>
- <div class="col-sm-6">
- <input type="text" class="form-control form-control-user" style="border-radius: 0rem !important" id="exampleLastName" [(ngModel)]="users.city" name="city" placeholder="City">
- </div>
- </div>
- <div class="form-group">
- <input type="text" class="form-control form-control-user" style="border-radius: 0rem !important" id="exampleInputEmail" [(ngModel)]="users.email" name="email" placeholder="Email Address">
- </div>
- <div class="form-group row">
- <div class="col-sm-6 mb-3 mb-sm-0">
- <input type="text" class="form-control form-control-user" style="border-radius: 0rem !important" id="exampleInputPassword" [(ngModel)]="users.password" name="password" placeholder="Password">
- </div>
- <div class="col-sm-6 mb-3 mb-sm-0">
- <input type="text" class="form-control form-control-user" style="border-radius: 0rem !important" id="exampleInputPassword" [(ngModel)]="users.department" name="department" placeholder="Department">
- </div>
-
- </div>
- <input type="submit" value=" Register Account" style="border-radius: 0rem !important" class="btn btn-primary btn-user btn-block"/>
- Register Account
- <!-- </button> -->
- <hr>
-
- </form>
- <hr>
- </div>
- </div>
- </div>
- </div>
- </div>
-
- </div>
Now open app.component.html file and add the following code.
- <div id="wrapper">
- <app-left-sidebar></app-left-sidebar>
- <div id="content-wrapper" class="d-flex flex-column">
- <div id="content">
- <app-header></app-header>
- <app-home></app-home>
- </div>
- </div>
- </div>
Now open app.module.ts file and add the following code.
- import { BrowserModule } from '@angular/platform-browser';
- import { NgModule } from '@angular/core';
- import { HeaderComponent } from "./layout/header/header.component";
- import { LeftSidebarComponent } from "./layout/left-sidebar/left-sidebar.component";
- import { HomeComponent } from "./layout/home/home.component";
- import { AppComponent } from './app.component';
- import { FormsModule } from '@angular/forms';
- import { HttpClientModule } from "@angular/common/http";
- @NgModule({
- declarations: [
- AppComponent,HomeComponent,LeftSidebarComponent,HeaderComponent
- ],
- imports: [
- BrowserModule,FormsModule,HttpClientModule
- ],
- providers: [],
- bootstrap: [AppComponent]
- })
- 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
- CREATE TABLE [dbo].[EmployeeLogin](
- [Id] [int] IDENTITY(1,1) NOT NULL,
- [Email] [varchar](50) NULL,
- [Password] [varchar](50) NULL,
- [EmployeeName] [varchar](50) NULL,
- [City] [varchar](50) NULL,
- [Department] [varchar](50) NULL,
- CONSTRAINT [PK_EmployeeLogin] PRIMARY KEY CLUSTERED
- (
- [Id] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
-
- 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
- public class Register
- {
- public int Id { get; set; }
- public string Email { get; set; }
- public string Password { get; set; }
- public string EmployeeName { get; set; }
- public string City { get; set; }
- public string Department { get; set; }
- }
Response Class
- public class Response
- {
- public string Status { set; get; }
- public string Message { set; get; }
-
- }
Right-click on the Controllers folder and add a new controller. Name it as "Employee controller" and add the following namespace.
- using LoginWithReacthooks.Models;
Create two methods in this controller to insert and getdetails and add the following code in this controller.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- using LoginWithReacthooks.Models;
- namespace LoginWithReacthooks.Controllers
- {
- public class employeeController : ApiController
- {
- RestaurantsEntities DB = new RestaurantsEntities();
- [Route("InsertEmployee")]
- [HttpPost]
- public object InsertEmployee(Register Reg)
- {
- try
- {
- EmployeeLogin EL = new EmployeeLogin();
-
- EL.EmployeeName = Reg.EmployeeName;
- EL.City = Reg.City;
- EL.Email = Reg.Email;
- EL.Password = Reg.Password;
- EL.Department = Reg.Department;
- DB.EmployeeLogins.Add(EL);
- DB.SaveChanges();
- return new Response
- { Status = "Success", Message = "Record SuccessFully Saved." };
-
- }
- catch (Exception)
- {
-
- throw;
- }
-
- }
-
- [Route("Getdetaisl")]
- [HttpPost]
- public object Getdetaisl()
- {
- return DB.EmployeeLogins.ToList();
- }
- }
- }
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,
Now go to vs code and run the project using the following command 'npm start'.