Share Data Between Sibling Components In Angular Using Rxjs BehaviorSubject

Here, we will discuss how to share data between sibling components using Rxjs Behavior Subject in Angular 5 project with step by step demonstration. As we know, we can share data between components in the different scenario like parent component to child component, child component to parent component, one component to another component which is siblings etc. And there are different ways available to share data between components like using Services, Event or Ngrx Store but these can be used as per their feasibility. Here, we will only discuss how we can share data between siblings component. So, let start practical demonstration and see how to achieve this.

For this practical implementation, we will use API which we have already created in the previous article. Here, we are using ASP.NET Core Web API with Oracle database. This API will show the list of employees and its details if we provide Employee Id as well. So, don't be confused if we make any HTTP call inside this demonstration. Please visit my previous article How to create Asp.Net Core Web API with Oracle database and Dapper ORM.

RxJS is a library for composing asynchronous and event-based programs by using observable sequences. It provides one core type, the Observable, satellite types (Observer, Schedulers, Subjects) and operators inspired by Array#extras (map, filter, reduce, every, etc) to allow handling asynchronous events as collections.

More about RxJS, Read Here.

Create Angular 5 Project

To create Angular 5 project, open Visual Studio Code [We can also use other editors like Visual Studio, Plnkr etc.] and press Ctrl+`. It will open a terminal window inside Visual Studio Code. Where we have to type following CLI command to create new Angular 5 project. 

ng new BehaviorSubjectDemo --routing

To know more about how to create Angular 5 CLI project step by step, you can follow my previous article "Building Angular 5 CLI project with ngx-bootstrap". Once you execute the command it will create an Angular 5 CLI project for you. Now, its time to run the project and see "is everything working fine?". To run the project, we have to fire one more command as follows.

ng serve --open

Below screenshot is the final architecture of this application after adding required components and service.

Angular

Add Bootstrap CDN

Once the project is ready and runs smoothly. First, we have to add bootstrap in the project so that we can easily access and implement bootstrap controls like textbox, dropdown etc. So, here I am not going to install bootstrap using  "npm install bootstrap" process. To make it simple, just adding bootstrap CDN with Index.html page. We can also install bootstrap using NPM and use it to import it into the styles.scss file which is nothing but main CSS file. We can see that we have added bootstrap CDN path just before the end of body tag.

  1. <!doctype html>  
  2. <html lang="en">  
  3. <head>  
  4.   <meta charset="utf-8">  
  5.   <title>BehaviorSubjectDemo</title>  
  6.   <base href="/">  
  7.   
  8.   <meta name="viewport" content="width=device-width, initial-scale=1">  
  9.   <link rel="icon" type="image/x-icon" href="favicon.ico">  
  10. </head>  
  11. <body>  
  12.   <app-root></app-root>  
  13.   <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">  
  14. </body>  
  15. </html>  

Create Employee Service

As we have already discussed, this application will use API which is already created and show the list of employees and employee details. So, let's create new service file in Angular 5 project inside service folder and name as "EmployeeService". This service is responsible for getting the list of data for the employee when a user clicks on the button "Get Employee List" and get the employee detail when a user clicks any of the employee rows from the table.

We can see with below code, here we have created one base URL, which is nothing but our API Base URL which is running locally. Apart from this, we have one method "getEmployeeList()" which will get the list of the employee from the Oracle database. Just move to next method which is "sendEmployeeDetail(id: number)". It takes one parameter as an employee id and gets the details for that particular employee. 

Here we are using Next() function of the Rxjs/BehaviorSubject which set the current value of the object and if any observer is looking for it then it will update the value for that observer. The observer will not be directly calling "sendEmployeeDetail()" but it will be associated with some other method which is returning Observable data and the observer will subscribe to it. 

  1. import { Injectable } from "@angular/core";  
  2. import { HttpClient } from "@angular/common/http";  
  3. import { Employee } from "../data/employee";  
  4. import { Observable, BehaviorSubject } from "rxjs";  
  5.   
  6.   
  7. @Injectable()  
  8. export class EmployeeService {  
  9.   
  10.     private baseURL: string;  
  11.     private empDetailSubject = new BehaviorSubject(null);  
  12.   
  13.     constructor(private http: HttpClient) {  
  14.         this.baseURL = 'http://localhost:60769/';  
  15.     }  
  16.   
  17.     getEmployeeList() {  
  18.         return this.http.get<Employee[]>(this.baseURL + 'api/GetEmployeeList');  
  19.     }  
  20.   
  21.     sendEmployeeDetail(id: number) {  
  22.         let data = this.http.get<Employee>(this.baseURL + 'api/GetEmployeeDetails/'+id);  
  23.         this.empDetailSubject.next(data);  
  24.     }  
  25.   
  26.     getEmployeeDetail(){  
  27.         return this.empDetailSubject.asObservable();  
  28.     }  
  29. }  

Enable CORS in Asp.Net Core Web API

As we using Asp.Net Core Web API project for creating API. To use it and getting data from API on your angular project, first, we have to enable CORS in the API. So, if you have created any Web API then you can enable CORS, but for me, we are using API created in the previous article. So, just go to that code and enable CORS adding following line of code.

  1. app.UseCors(builder => builder.WithOrigins("http://localhost:4300").AllowAnyMethod().AllowAnyHeader());  
  2. using Core2API.Repositories;  
  3. using Microsoft.AspNetCore.Builder;  
  4. using Microsoft.AspNetCore.Hosting;  
  5. using Microsoft.Extensions.Configuration;  
  6. using Microsoft.Extensions.DependencyInjection;  
  7.   
  8. namespace Core2API  
  9. {  
  10.     public class Startup  
  11.     {  
  12.         public Startup(IConfiguration configuration)  
  13.         {  
  14.             Configuration = configuration;  
  15.         }  
  16.   
  17.         public IConfiguration Configuration { get; }  
  18.   
  19.         // This method gets called by the runtime. Use this method to add services to the container.  
  20.         public void ConfigureServices(IServiceCollection services)  
  21.         {  
  22.             services.AddTransient<IEmployeeRepository, EmployeeRepository>();  
  23.             services.AddSingleton<IConfiguration>(Configuration);  
  24.             services.AddMvc();  
  25.         }  
  26.   
  27.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  28.         public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
  29.         {  
  30.             if (env.IsDevelopment())  
  31.             {  
  32.                 app.UseDeveloperExceptionPage();  
  33.             }  
  34.               
  35.             //Enable CORS  
  36.             app.UseCors(builder => builder.WithOrigins("http://localhost:4300").AllowAnyMethod().AllowAnyHeader());  
  37.               
  38.             app.UseMvc();  
  39.         }  
  40.     }  
  41. }  

Create Employee.ts

So, let create one interface which is nothing but defining the type of the result which will return from the database. Create an interface "Employee" with its properties as follows.

  1. export interface Employee{  
  2.     ID: number,  
  3.     NAME: string,  
  4.     SALARY: number,  
  5.     ADDRESS: string  
  6. }  

Create two new components

Now we will create two new components as "EmployeeList" and "EmployeeDetail" using the following commands in "components" folder. 

 

  • ng g c EmployeeList --save
  • ng g c EmployeeDetail --save

 

Update App.Module.ts

So, we have service ready which will bring data from a database and created two components which will display contents. Now we have to update our main module "AppModule" and add service in "Providers", so that service can access anywhere in components which are related to AppModule and components in "Declarations" section. As we can see with below code how we have added our components and service and imported from their location. Please kind attention with import statements, we are importing "HttpClientModule" for HTTP operation and "FormsModule" for using inbuilt directives like *ngFor, *ngIf etc.

  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import { HttpClientModule } from '@angular/common/http';  
  4. import { FormsModule } from '@angular/forms';  
  5.   
  6. import { AppComponent } from './app.component';  
  7. import { EmployeeListComponent } from './components/employee-list/employee-list.component';  
  8. import { EmployeeDetailComponent } from './components/employee-detail/employee-detail.component';  
  9. import { EmployeeService } from './sevices/employee.service';  
  10.   
  11.   
  12. @NgModule({  
  13.   declarations: [  
  14.     AppComponent,  
  15.     EmployeeListComponent,  
  16.     EmployeeDetailComponent  
  17.   ],  
  18.   imports: [  
  19.     BrowserModule,  
  20.     HttpClientModule,  
  21.     FormsModule  
  22.   ],  
  23.   providers: [EmployeeService],  
  24.   bootstrap: [AppComponent]  
  25. })  
  26. export class AppModule { }  

App.component.html and App.component.ts

Move to "App.component.html", basically it's parent component. So, here we are going to add a button, which will get the list of the employee when we click on it and add "<app-employee-list></app-employee-list>" and <<app-employee-detail></app-employee-detail>" templates for showing the list of employee and employee's detail respectively. 

So, basically "EmployeeListComponent" and "EmployeeDetailComponent" are the child component of "AppComponent".

  1. <div class="container">  
  2.   <div class="row">  
  3.     <h2>Employee Portal</h2>  
  4.   </div>  
  5.   <div class="row">  
  6.     <fieldset class="for-panel">  
  7.       <legend>Contact Info</legend>  
  8.       <div class="row">  
  9.         <div class="col-sm-6">  
  10.           <button (click)="getEmployeeList()" class="btn btn-primary">Get Employee List</button>  
  11.           <br>  
  12.           <br>  
  13.         </div>  
  14.       </div>  
  15.       <div class="row"></div>  
  16.       <div class="row">  
  17.         <div class="col-sm-6">  
  18.           <app-employee-list [empListData]="empList"></app-employee-list>  
  19.         </div>  
  20.         <div class="col-sm-6">  
  21.           <app-employee-detail></app-employee-detail>  
  22.         </div>  
  23.       </div>  
  24.     </fieldset>  
  25.   </div>  
  26. </div>  

With following AppComponent code, you can see, service is injected with a constructor. And the method "getEmployeeList()" is getting the list of employees from service and bind data to "empList" variable which is employee array type.

  1. import { Component } from '@angular/core';  
  2. import { EmployeeService } from './sevices/employee.service';  
  3. import { Employee } from './data/employee';  
  4.   
  5. @Component({  
  6.   selector: 'app-root',  
  7.   templateUrl: './app.component.html',  
  8.   styleUrls: ['./app.component.css']  
  9. })  
  10. export class AppComponent {  
  11.   empList: Employee[];  
  12.   
  13.   constructor(private employeeService: EmployeeService) {      
  14.   }  
  15.   
  16.   getEmployeeList() {  
  17.     this.employeeService.getEmployeeList().subscribe(data => {  
  18.       this.empList = data;  
  19.     });  
  20.   }  
  21.   
  22. }  

Employee-list.component.html and Employee-list.component.ts

Following code is for showing list of the employee in the tabular format. Here we are using a table for constructing header and its data something like a grid. In body part of the table, you will notice, to iterate the data, we are using *ngFor along with click event on the row. When we click on any row then click event will be fire and it will send the "employee id" for the selected row for getting the individual detail of employee.

  1. <div class="panel panel-primary">  
  2.   <div class="panel-heading">  
  3.     <h3 class="panel-title">Employee List</h3>     
  4.   </div>  
  5.   <table class="table table-hover" id="dev-table">  
  6.     <thead>  
  7.       <tr>  
  8.         <th>Id</th>  
  9.         <th>Name</th>  
  10.         <th>Salary</th>  
  11.         <th>Address</th>  
  12.       </tr>  
  13.     </thead>  
  14.     <tbody>  
  15.       <tr *ngFor='let item of empListData' (click)="sendEmployeeDetail(item.ID)">  
  16.         <td>{{item.ID}}</td>  
  17.         <td>{{item.NAME}}</td>  
  18.         <td>{{item.SALARY}}</td>  
  19.         <td>{{item.ADDRESS}}</td>  
  20.       </tr>  
  21.     </tbody>  
  22.   </table>  
  23. </div>  

Following is EmployeeListComponent class where you can notice that "empListData" is coming from parent components.

  1. import { Component, OnInit, Input } from '@angular/core';  
  2. import { Employee } from '../../data/employee';  
  3. import { EmployeeService } from '../../sevices/employee.service';  
  4. //import { FormGroup, FormControl } from '@angular/forms';  
  5.   
  6. @Component({  
  7.   selector: 'app-employee-list',  
  8.   templateUrl: './employee-list.component.html',  
  9.   styleUrls: ['./employee-list.component.css']  
  10. })  
  11. export class EmployeeListComponent implements OnInit {  
  12.   
  13.   @Input() empListData: Employee[];  
  14.   constructor(private employeeService: EmployeeService) {     
  15.   }  
  16.   
  17.   sendEmployeeDetail(id: number){  
  18.     this.employeeService.sendEmployeeDetail(id);  
  19.   }  
  20.   
  21.   ngOnInit() {  
  22.   }  
  23. }  

Employee-detail.component.html and Employee-detail.component.ts

Now its time to show an individual detail of employee when we select or click any of the rows from the list of the employee. Here we are binding data from "employeeDetail" but as it is an observable so we can not directly access data. To access data from observable, we have to use aysnc pipe and provide some dummy name like "item" and then we will be able to access that data through the item.

  1. <div class="form-horizontal" *ngIf="employeeDetail | async as item">  
  2.   <h3>Employee Detail</h3>  
  3.   <br>  
  4.   <label class="col-xs-4 control-label">ID: </label>  
  5.   <p class="form-control-static">{{item[0].ID}}</p>  
  6.   
  7.   <label class="col-xs-4 control-label">NAME:</label>  
  8.   <p class="form-control-static">{{item[0].NAME}}</p>  
  9.   
  10.   <label class="col-xs-4 control-label">SALARY:</label>  
  11.   <p class="form-control-static">{{item[0].SALARY}}</p>  
  12.     
  13.   <label class="col-xs-4 control-label">ADDRESS:</label>  
  14.   <p class="form-control-static">{{item[0].ADDRESS}}</p>  
  15. </div>  

When clicking on any row from the list of employee, we load this employee detail page and its ngOnInit() event, which will get the employee details and bind with "employeeDetail" variable using the employee service.

  1. import { Component, OnInit } from '@angular/core';  
  2. import { EmployeeService } from '../../sevices/employee.service';  
  3. import { Employee } from '../../data/employee';  
  4.   
  5. @Component({  
  6.   selector: 'app-employee-detail',  
  7.   templateUrl: './employee-detail.component.html',  
  8.   styleUrls: ['./employee-detail.component.css']  
  9. })  
  10. export class EmployeeDetailComponent implements OnInit {  
  11.   
  12.   employeeDetail: Employee;  
  13.     
  14.   constructor(private employeeService: EmployeeService) {    
  15.   }  
  16.   
  17.   ngOnInit() {  
  18.     this.employeeService.getEmployeeDetail().subscribe(data => { this.employeeDetail = data });  
  19.   }  
  20. }  

Here we have modified some css as following to look good table and all.

  1. /* You can add global styles to this file, and also import other style files */  
  2. fieldset.for-panel {  
  3.     background-color: #fcfcfc;  
  4.     border: 1px solid #999;  
  5.     border-radius: 4px;   
  6.     padding:15px 10px;  
  7.     background-color: #d9edf7;  
  8.     border-color: #bce8f1;  
  9.     background-color: #f9fdfd;  
  10.     margin-bottom:12px;  
  11. }  
  12. fieldset.for-panel legend {  
  13.     background-color: #fafafa;  
  14.     border: 1px solid #ddd;  
  15.     border-radius: 5px;  
  16.     color: #4381ba;  
  17.     font-size: 14px;  
  18.     font-weight: bold;  
  19.     line-height: 10px;  
  20.     margin: inherit;  
  21.     padding: 7px;  
  22.     width: auto;  
  23.     background-color: #d9edf7;  
  24.     margin-bottom: 0;  
  25. }  

Now run the application using the command "ng serve" and it will show the screen similar to below image if you have changed all CSS as per my demonstration. Here I am using port 4300 but by default, it is 4200. So, don't need to confuse for the port. Here you can see employee portal page, where we have a button "Get Employee List" and just below we have one table for employee List. 

Angular

If we click on the button "Get Employee List" then it will get the data from the Oracle database using Asp.Net Core API and fill the following table as shown in the image below. So, now you can see we have four records showing inside the table.

Angular

 

Now let click any of the rows for employee detail. let say, I am clicking on which have employee id as 102. When I will click on that it will send the selected row employee id to the details page. And finally, data will be populated for employee detail just next to the list of the employee. 

Angular

 

Conclusion

So, today we have learned how to share data between sibling components using rxjs behavior subject in angular 5 application.

I hope this post will help you. Please put your feedback using comment which helps me to improve myself for next post. If you have any doubts please ask your doubts or query in the comment section and If you like this post, please share it with your friends. Thanks