Search code examples
angularbehaviorsubject

Subscribing to BehaviorSubject after reloading the dialog component


Here is the code I already have:

device.service.ts

import {Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs';


@Injectable({
  providedIn: 'root'
})
export class DeviceService {

  deviceList: any;

  private deviceListSource = new BehaviorSubject(this.deviceList);
  currentDeviceList = this.deviceListSource.asObservable();

  constructor(){}

  getDevices(): void {
    this.http.get<any>('https://........')
      .subscribe(data => {
        this.deviceListSource.next(data.data);
      }, error => console.log('Could not GET devices.'));
  }

And my dialog component looks like this:

devices.component.ts

  ngOnInit() {

      this.deviceService.getDevices();
      this.deviceService.currentDeviceList.subscribe(data => {
      console.log(data)
    });
  }

This works great for sharing some values between several components. When I close the dialog (which is devices.component.ts) and reopen it again without reloading the whole page, the console.log(data) command is executed as many times as I already opened/closed the dialog. So when I open the dialog it subscribes to all the values which were added by the service by .next() one after another. But I want the dialog only to subscribe to the last value added by the service.

As I understood this BehaviorSubject is exactly for this usecase. Is there something I missed? Or is there another (better) way to achieve that?


Solution

  • Kill your subscription once you close your dialog.

    someSubscription: Subscription
    ngOnInit() {
          this.deviceService.getDevices();
          this.someSubscription = this.deviceService.currentDeviceList.subscribe(data => {
          console.log(data)
        });
    }
    
    
    ngOnDestroy() {
        if (this.someSubscription) {
            this.someSubscription .unsubscribe();
        }
    }