gpt4 book ai didi

Angular RxJs BehaviorSubject 没有正确更新

转载 作者:搜寻专家 更新时间:2023-10-30 21:22:25 25 4
gpt4 key购买 nike

我正在尝试从同级组件(​​灯光开关到导航栏)共享一个字符串值。我的问题是,当我从 DataService 发出新值时,属性 themeColor 没有得到更新。

这是我的 App.Component.html 的结构:

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

我正在尝试使用数据服务:

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

}

这是我的 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");
}
}

还有我的 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});
}
}

导航栏.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>

我的 App.Module.ts 中有 DataService 作为提供者。当 ngOnInit 在 navbar.ts 中运行时,它确实获得了我设置的默认值,当我在 light-switch.ts 中调用 changeThemeColor() 时,它确实进入了 DataService .ts 并更改 currentColor 属性,但同样,navbar.ts 中的 themeColor 属性不会更新为 currentColor 属性。我怀疑我需要某种事件监听器才能正确地将值从 DataService 获取到导航栏,但我认为这就是我订阅的内容。

最佳答案

您的代码看起来基本上是正确的。

您的 DataService 是否可能未正确注册并且您没有获得单例?您的 DataService 的提供程序数组是否在模块中?还是一个组件?还是在多个组件中?

确保服务只在一个地方注册(添加到提供程序数组)。

关于Angular RxJs BehaviorSubject 没有正确更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49040743/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com