Home > OS >  Not getting the updated value of an rxjs BehaviorSubject in a component
Not getting the updated value of an rxjs BehaviorSubject in a component

Time:05-23

I'm working on this photo editor app where changes are auto-saved in the db. Now I'm trying to add a toast that would display when the editor data is saved to db successfully. So I'm using RxJS's BehaviorSubject to achieve that.

Please note that the editor changes are first sent to a service called DataProcessService where it is processed and then an API call is made which is in another service. Also in DataProcessService, I have set up the logic for the BehaviorSubject.

This is how the code in DataProcessService looks like now:

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

@Injectable({
    providedIn: 'root'
})
class DataProcessService {

  private toast = new BehaviorSubject<boolean>( false );
  currentToastState = this.toast.asObservable()

  private constructor( private apiService: ApiService ) {}

  changeToastState( state: boolean ): void {
     this.toast.next( state );
  }

  process( data ) { 
   
    // got rid of data processing for simplicity
    
    this.apiService.postData( data )
      .then( response => {
        console.log('Success');
        this.changeToastState( true );
      })
      .catch( error => {
        console.log('Error: ', error);
      })
  }

}

This is the PhotoEditorComponent:

@Component({
  selector: 'editor-page',
  templateUrl: './editor.component.html',
  styleUrls: ['./editor.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})

class PhotoEditorComponent implements OnInit {

  @ViewChild('toast');

  toast: ToastComponent;
  isToast: boolean;

  private constructor( private dataProcessService: DataProcessService ) {}

  ngOnInit(): void {

    this.dataProcessService.currentToastState.subscribe( state => {
      this.isToast = state;
    });

    console.log( 'Log 1: ', this.isToast );

    if ( this.isToast ) {
      console.log( 'Log 2: ', this.isToast );
      this.successMessage = 'Saved successfully!;
      this.ref.detectChanges();
      this.toast.show();
      this.dataProcessService.changeToastState( false );
    }

  }

}

Please note that Log 1 is false when I refresh the page. And when there is a change in the editor it does not turn it to true or whatsoever. Log 2 never fires```

CodePudding user response:

this 'if block' should be in subscribe block I guess!

if ( this.isToast ) {
      console.log( 'Log 2: ', this.isToast );
      this.successMessage = 'Saved successfully!;
      this.ref.detectChanges();
      this.toast.show();
      this.dataProcessService.changeToastState( false );
    }
  • Related