Sharing data between components in Angular 8

Method 1: Pass data from one component to another component in Angular 8

I am happy to share you the live scenario of passing data from one component to another component.

Scenario :

I need to display the login name which i have entered in Login screen to be passed to the Dashboard screen,In Dashboard screen, the login name will be displayed in the top right corner of the browser which is nearer to the logout button.

                        //create one behavioursubject and one observable
                        private sendusernamebsdata= new BehaviourSubject("nousersent");
                        userbehaviourobservable=new Observable;
                        this.userbehaviourobservable = this.sendusernamebsdata.asObservable();
Passing Username from login component.ts(LOGIN SCREEN)
                            this.dataservice.sendusernametoothercomponents(this.loginform.controls.username.value); //passed to dashboard component
                        this.usernamesubjscription= this.dataservice.userbehaviourobservable.subscribe(
Method 2: Sharing data with Service

Let us use Rxjs BehaviourSubject,The following things can be achieved using Rxjs Behaviour subject.
1.I can get current value on subscription.
2.It has getValue() function to extract the last value.
In the Data service, we create private behavioursubject that has current value of message.Now create currentmessage variable as an Observable.Suppose if you want to change the value of the message then create a function called ChangeYourMessage() where you will call next() on the BehaviourSubject to change its value dynamically by child components. You can call this ChangeYourMessage() in any component and you can pass the message from this component and this message will be reflected in the view.

import {Injectable} from '@angular/core';
import {BehaviourSubject} from 'rxjs';
export class ShareDataService
    private defaultdata=new BehaviourSubject('Hello USMTECHWORLD');


<div style="padding:10px;border:1px solid black">
    I am component 1 
<button (click)="button1click()">COMPONENT 1<button>
This is default message of service <font color="red"> {{message}} <font>
Now click component 2 button and see what happens <div>


<div style="padding:10px;border:1px solid black">
I am component 2 
<button (click)="button1click()">COMPONENT 2<button>
This is default message of service <font color="blue"> {{message}} <font>
click component 1 button u can see the default message is changed now and that message is sent from component1 <div>