Angular+sharing data bw components


Sharing data between components


 Service:



import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
 
@Injectable({
    providedIn: 'root'
})
export class AppService {
    counter = 1;
    count: BehaviorSubject<number>;
    constructor() {
 
        this.count = new BehaviorSubject(this.counter);
    }
 
    nextCount() {
        this.count.next(++this.counter);
    }
}

Now components can consume service to access shared data. For example, in a component, service can be consumed as shown in the next listing:

export class Appchild2Component implements OnInit {
 
    count: number;
    constructor(private appsevice: AppService) {
    }
    ngOnInit() {
 
        this.appsevice.count.subscribe(c => {
            this.count = c;
        });
    }
    nextCount() {
        this.appsevice.nextCount();
    }
}

 

We are subscribing to service and reading the value of count in the local variable. In addition, there is a function that  increments the count.  On the template, you can display and increment shared data as shown in the next code listing:

<h2>Count in component2  =  {{ count }}</h2>
<button (click)='nextCount()'>Next Count from component2</button>

In this way, you can consume service in as many components as possible and everywhere they will share the same data from the service. For your reference you can find working stackblitz here:

https://stackblitz.com/github/debugmodedotnet/componnetcommunicationwithservice



Parent child component relationship:

https://fireship.io/lessons/sharing-data-between-angular-components-four-methods/

 In my opinion




----------------------------------------shared service--------------------------------------------------------------------------------

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { BehaviorSubject, Observable } from 'rxjs';
import { AuthenticateResponse } from '../model/AuthenticateResponse';

@Injectable({
  providedIn: 'root'
})
export class SharedService {
 
  public currentUserSubject!: BehaviorSubject<any>;

  //using this we can subscribe latest value
  public currentUser!: Observable<any>;


  constructor(private router: Router) {
    this.currentUserSubject = new BehaviorSubject<any>(JSON.parse(localStorage.getItem('currentUser')!));
        this.currentUser = this.currentUserSubject.asObservable();
   }
   


   //get current user with out subscribe
   public get currentUserValue() {
    return this.currentUserSubject.value;
}




//push item into BehaviorSubject
PushLatestItemValues(data:any){
  this.currentUserSubject.next(data)
}
 

}


//check login in login constructor

//if login redirect
    if (this.sharedService.currentUserValue) {
      console.log(this.sharedService.currentUserValue);
      this.router.navigate(['/Home']);
  }


using subscribe in constructor

 this.sharedservice.currentUser.subscribe(x => this.currentUser = x);
    console.log(this.currentUser);

//used for login/logout show hide
 <li class="nav-item"  *ngIf="!currentUser" >
            <a class="nav-link" [routerLink]="['/login']">Login</a>
          </li>
          <li class="nav-item"  *ngIf="currentUser" >
            <a class="nav-link"  (click)="logout()">LogOut</a>
          </li>



Comments