Noa*_*nak 3 rxjs typescript angular
我正在尝试从同级组件(灯开关到导航栏)共享一个字符串值。我的问题是财产themeColor当我从 DataService 发出新值时没有得到更新。
这是我的 App.Component.html 的结构:
<navbar></navbar>
<banner><light-switch></light-switch></banner>
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用 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)
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的 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");
}
}
Run Code Online (Sandbox Code Playgroud)
还有我的 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});
}
}
Run Code Online (Sandbox Code Playgroud)
导航栏.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>
Run Code Online (Sandbox Code Playgroud)
灯开关.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>
Run Code Online (Sandbox Code Playgroud)
我在 App.Module.ts 中有 DataService 作为提供者。当ngOnInit在navbar.ts运行时,它得到的默认值设定的我,当我打电话changeThemeColor()的光switch.ts,它进入DataService.ts并更改currentColor属性,但再次重申,themeColor在navbar.ts属性不更新到该currentColor属性。我怀疑有某种事件侦听器需要正确地从 DataService 获取值到导航栏,但我认为这就是我订阅的内容。
Deb*_*ahK 13
您的代码看起来基本正确。
是否有可能您的 DataService 未正确注册并且您没有获得单身人士?您的 DataService 的 providers 数组是否在模块中?还是组件?还是在多个组件中?
确保服务仅在一处注册(添加到提供者数组)。
| 归档时间: |
|
| 查看次数: |
6018 次 |
| 最近记录: |