I've encountered an issue while attempting to share a string value between sibling components (light-switch and navbar). The problem lies in the fact that the property themeColor
fails to update when I emit a new value from my DataService.
Below is the structure of my App.Component.html:
<navbar></navbar>
<banner><light-switch></light-switch></banner>
I'm using a DataService for this purpose:
import {Injectable} from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class DataService {
private themeColor = new BehaviorSubject<string>("#f5f0f0");
currentThemeColor = this.themeColor.asObservable();
constructor() { }
changeThemeColor(color: string) {
this.themeColor.next(color)
}
}
Here is my light-switch.component.ts file:
import { Component, OnInit } from '@angular/core';
import {DataService} from "./../Services/DataService";
@Component({
selector: 'light-switch',
templateUrl: './light-switch.component.html',
styleUrls: ['./light-switch.component.scss']
})
export class LightSwitchComponent implements OnInit {
public currentTheme;
public themeColor;
constructor(private sanitization: DomSanitizer, private dataService: DataService) {
this.currentTheme = "dark";
this.themeColor = "#f5f0f0";
}
ngOnInit() {
this.dataService.currentThemeColor.subscribe(color =>{ this.themeColor = color});
}
changeToLight(){
this.dataService.changeThemeColor("black");
}
changeToDark(){
this.dataService.changeThemeColor("#f5f0f0");
}
}
Now, let's take a look at navbar.ts:
import { Component, OnInit } from '@angular/core';
import {DataService} from "./../Services/DataService";
@Component({
selector: 'navbar',
templateUrl: './navigation-bar.component.html',
styleUrls: ['./navigation-bar.component.scss']
})
export class NavigationBar implements OnInit {
private themeColor;
constructor(private dataService: DataService) {
}
ngOnInit() {
this.dataService.currentThemeColor.subscribe(color => {this.themeColor = color});
}
}
NavigationBar.html content:
<div class="navbar">
<i class="fa fa-github bannerIcon" id="githubIcon" [style.color]='themeColor'></i>
<i class="fa fa-linkedin bannerIcon" id="linkedInIcon" [style.color]='themeColor'></i>
</div>
And finally, here's what's inside light-switch.html:
<div id="lightSwitch">
<button class="btn btn-secondary switchBtn-on" (click)="changeToLight()">On</button>
<button class="btn btn-secondary switchBtn-off">Off</button>
</div>
I have made sure to include DataService as a provider in my App.Module.ts. Although in navbar.ts, upon running ngOnInit
, it does recognize the default value I originally set. However, despite calling changeThemeColor()
in light-switch.ts, the currentColor
property is updated within DataService.ts but unfortunately doesn't seem to reflect on the themeColor
property in navbar.ts. My suspicion is that perhaps there may be a need for an event listener to effectively capture the value from DataService to navbar, although I thought subscribing would handle this.