Search code examples
angularrxjsobservablebehaviorsubject

RxJS BehaviouSubject when using map operator in service and subscribing in the component


I am new to BehaviourSubject in RxJS and I am trying to use it to share data across components. I am not sure how exactly to use it. The code in my component is

export class CarsListComponent implements OnInit {
  cars: Cars[] = []; 
  constructor(private carsListService: CarsListService) { }


     ngOnInit() {
       this.carsListService.getCars()
      .subscribe(response => {
      this.cars= response;
      }, error => {
       console.log(error);
      });
     }
}

The code in my service is

 export class CarsService {

 constructor(private http: HttpClient) {}

 getCars(): Observable<Car[]> {
    return this.http.get<Car[]>(url,headers)
    .pipe(
        map(response => response)
    );
 }
}

I don't know how to use BehaviourSubject and how to implement it. Please help me out with this.


Solution

  • From the question i think you are trying to use the same this.cars across multiple components . If you want to share it then using BehaviorSubject is one way to do it as it stores the value even if already subscribed to it.

    Let's create a shared service that will be injected into multiple components say app-shared.service.ts

    app-shared.service.ts :

    import { Injectable } from '@angular/core';
    import { BehaviorSubject , Observable} from 'rxjs';
    
    @Injectable()
    export class AppSharedService {
    
      carsListSubjectt : BehaviorSubject<Cars[]> = new BehaviorSubject<Cars[]>([]);
    
      constructor() { }
    
    
      updateCarsList(cars : Cars[]) : void{
        this.carsListSubjectt.next(cars);
      }
    
    
      getCarsList() : Observable<Cars[]>{
        return this.carsListSubjectt.asObservable();
      }
    
    }
    
    
    
    export interface Cars{
      carType : string ;
      manufacturedDate : Date;
      condition : string;
    }
    

    Note : Cars interface is just my definition . Use your definition .

    Now you just have to inject the app-shared.service in your required component.

    To update data , using your code :

    export class CarsListComponent implements OnInit {
      cars: Cars[] = []; 
      constructor(private carsListService: CarsListService, private _appSharedService : AppSharedService) { }
    
    
         ngOnInit() {
           this.carsListService.getCars()
          .subscribe(response => {
          this.cars= response;
          this._appSharedService.updateCarsList(response);
          }, error => {
           console.log(error);
          });
         }
    }
    

    You just have to subscribe to the getCarsList() defined in the app-shared.service as it is going to return an Observable<Cars[]> .

    Let me know if this helps :)