Angular RxJs BehaviorSubject not updating properly

Noah Hornak

I'm trying to share a string value from sibling components(light-switch to navbar). My problem is that the property themeColor is not getting updated when I emit the new value from my DataService.

Here is my structure for my App.Component.html:

<navbar></navbar>
<banner><light-switch></light-switch></banner>

I'm trying to use a DataService:

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)
  }

}

This is my light-switch.component.ts:

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");
  }
}

And my 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:

<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>

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 DataService as a provider in my App.Module.ts. When ngOnInit runs in navbar.ts, it does get the default value I set and when I call the changeThemeColor() in light-switch.ts, it does go into DataService.ts and change the currentColor property, but again, the themeColor property in navbar.ts does not update to that currentColor property. I suspect there is some sort of event listener I need to correctly get the value from DataService to navbar, but I thought that's what I subscribed for.

DeborahK

Your code looks basically correct.

Is it possible your DataService is not correctly registered and you aren't getting a singleton? Is the providers array for your DataService in a module? Or a component? Or in multiple components?

Ensure the service is only registered (added to the providers array) in one place.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Angular 2 rxjs observables created from BehaviorSubject are not working with forkJoin

Angular2 + RxJS BehaviorSubject subscription not working on all components

Angular 4 - rxjs BehaviorSubject usage in Service

RxJS 5, converting an observable to a BehaviorSubject(?)

RxJS: BehaviorSubject unsubscribe

deferred Rxjs BehaviorSubject mechanism

Any downside to always using BehaviorSubject instead of Subject (RxJs\Angular)?

Angular rxjs BehaviorSubject.value sets value without next(), not immutable

loading spinner using rxjs BehaviorSubject

Angular/rxjs/Subject/BehaviorSubject share http service data across multiple components

RxJS: BehaviorSubject and groupBy operator

Add elements to rxjs BehaviorSubject or Subject of an array in Angular2+

Angular 6 - Form - Select Option not updating properly

Rxjs strange problem with BehaviorSubject

RxJS - BehaviorSubject, onComplete not called

Filter and transform rxjs BehaviorSubject

RXJS BehaviorSubject getValue vs value

Angular: RxJS Observable only updating on timeout

BehaviorSubject RxJs angular2

Angular: Share data dynamically between components using RxJs/BehaviorSubject

Angular and RxJS: Updating the Subject?

Angular BehaviorSubject not updating in time

How to properly chain concatMaps in Angular RxJS

Updating cached http request in Angular with RxJS and shareReplay

Angular/Typescript/RxJs: updating value of BehaviorSubject (Object Assign) while observing changes

Angular 12/rxjs: BehaviorSubject shall return empty object array, but returns undefined instead

how to use Rxjs filter in angular along with BehaviorSubject

Angular/RXJS: Changing values of an object from an observable changes its value in the BehaviorSubject

Angular is not updating view with boolean variable in the rxjs pipe

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    pump.io port in URL

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

  14. 14

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  15. 15

    How to use merge windows unallocated space into Ubuntu using GParted?

  16. 16

    flutter: dropdown item programmatically unselect problem

  17. 17

    Pandas - check if dataframe has negative value in any column

  18. 18

    Nuget add packages gives access denied errors

  19. 19

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  20. 20

    Generate random UUIDv4 with Elm

  21. 21

    Client secret not provided in request error with Keycloak

HotTag

Archive