0
votes

I am new to angular 9... I have an observable in my template (theme$), which is updating properly, and based on the value of this observable, I want to make changes via javascript in my component definition:

<div [class]="'headerWrapper ' + (theme$ | async)">

theme$ is an observable.

i am not sure what is the proper place to check for this value (ie subscribe to $theme) updating in my component, instead of relying on its updated value in the template. I tried ngOnChanges but that is only for @Input props. I want to write a method in my component class that will execute every time $theme changes (so not just ngOnInit).

my component:

ngOnInit() {
console.log(this, "THE THIS")
this.theme$ = this.dataService.currentTheme;}

my service which has the observable:

    import { BehaviorSubject } from 'rxjs';
    public themeSource = new BehaviorSubject('dark');
    currentTheme = this.themeSource.asObservable();
      
    toggleTheme(theme) {
      this.themeSource.next(theme)
    }
1

1 Answers

1
votes

Behavior subject will emit a new value whenever .next() gets called.

You can subscribe to the service_name.currentTheme in your component either in ngOnInit or ngAfterViewInit lifecycle hooks and the observer gets notified whenever there's a new emit.

Also, we create a new variable like currentTheme = this.themeSource.asObservable(); in your case just to ensure the behavior subject themeSource remains private to the service class and not be accessed outside the class.

So, please make the themeSource variable private like :: private themeSource = new BehaviorSubject('dark');

Hope this answers your question. Please add a comment if you have any doubt