Developer Snippet Diary

Share common data in other components in Angular using RxJS BehaviorSubject

In Web development, it is common for multiple components to require access to shared data that needs to be constantly updated. To address this need, a popular approach is to utilize a concept called BehaviorSubject. This powerful tool acts as a centralized store, ensuring that the shared data remains up to date for all components that rely on it.

By employing BehaviorSubject, developers can effectively manage the flow of information within their applications. This enables seamless communication and synchronization between different parts of the system. As a result, the components can always access the most recent version of the shared data, promoting consistency and accuracy across the board.

Using BehaviorSubject simplifies the process of handling shared data in complex applications. It serves as a reliable and efficient solution, facilitating smooth coordination between various components. By employing this approach, developers can enhance the overall performance and functionality of their software, providing an optimized user experience.

  • BehaviorSubject handles shared data updates among multiple components. It acts as both an observer and a type of observable.
  • One important thing to note is that BehaviorSubject requires an initial or default value. This value serves as a starting point for the shared data.
  • When a component subscribes to BehaviorSubject, it immediately receives the current value. This value can be either the most recent one emitted by the source observable using the next() method, or it can be the initial/default value.
  • Overall, BehaviorSubject simplifies the management of shared data by providing an updated value to all observers. It ensures consistency and accuracy across components, making it easier to work with shared data in software applications.

First of all create a service

  1. Open your command prompt or terminal.
  2. Navigate to your Angular project's root directory using the cd command.
  3. Use the Angular CLI command ng generate service (or ng g s for short) followed by the desired name for your service. For example, if you want to create a service called ApiService you can run the following command:
    ng generate service ApiService
//api.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable,BehaviorSubject, throwError } from 'rxjs';
@Injectable({
  providedIn: 'root'
})
export class ApiService {
  constructor(private http: HttpClient) { }
private user_fav_items = new BehaviorSubject<any>(null);
  current_fav_items = this.user_fav_items.asObservable();
  updateUserFavItems(data: any) {
    this.user_fav_items.next(data);
  }
  get(url: string): Observable<any> {
    return this.http.get<any>(url);
  }

}

header.component.ts

export class HeaderComponent {
  constructor(private apiService: ApiService, private cookieService: CookieService) { }
  ngOnInit(){
      const url = environment.apiUrl+'/favourite_list?user_id='+this.cookieService.get('id');
      this.apiService.get(url).subscribe(
        (response) => {
          if(response.flag){           
            this.apiService.updateUserFavItems(response);
          }
        },
        (error) => { console.error(error); }
      );
    }
  }

access data inside footer.component.ts

ngOnInit(){
    this.apiService.current_fav_items.subscribe(data => {
      if (data) {
        console.log("favs",data);
      }
    });
}
Posted by: R GONDAL
Email: rizikmw@gmail.com