布尔可观察值未在组件之间传递



我使用angular4作为仪表板,当用户在单独的组件中单击div时,Im绑定以隐藏一个div。我创建了一个具有布尔可观察值的服务,但是当我单击按钮隐藏div 时,服务会使用新值更新,但另一个div 没有检测到更改

服务

import { Injectable } from '@angular/core';
import { BehaviorSubject } from "rxjs/BehaviorSubject";

@Injectable()
export class ToggleParamsService {

toggleReportAgeSentiment: BehaviorSubject<boolean>;

constructor() {
this.toggleReportAgeSentiment = new BehaviorSubject<boolean>(true);
this.toggleReportAgeSentiment.asObservable();

}
toggleReportAgeSentiment(showHide: boolean)
{
this.toggleReportAgeSentiment.next(showHide) ;
}

}

这是我希望在更新参数时隐藏的组件。如果我登录到服务中的控制台,我可以看到正在进行的更新,但它没有进入此组件

元件

import {Component, Input, OnInit} from '@angular/core';
import {ToggleParamsService} from '../../../../shared/services/toggle-params-service/toggle-params.service';
@Component({
selector: 'app-report-age-by-sentiment',
providers: [ToggleParamsService],
templateUrl: './report-age-by-sentiment.component.html',
styleUrls: ['./report-age-by-sentiment.component.less']
})
export class ReportAgeBySentimentComponent implements OnInit {
@Input() episodeReport: any;
showHide;
constructor(private toggle: ToggleParamsService) { }   //
ngOnInit() {
this.toggle.toggleReportAgeSentiment.subscribe(showHide => this.showHide = showHide);

}

changeShowAgeSentiment(){
this.toggle.toggleReportAgeSentiment(!this.showHide);
}
}

模板

<div *ngIf="showHide == true">
<div class = "col-xs-4 col-xs-offset-8 col-sm-4 col-sm-offset-8 col-md-4 col-md-offset-8 col-lg-4 col-lg-offset-8 arrow-down" >
<!--<svg height="30" width="60" class="arrow-down-open">-->
<!--<polygon points="0,0 30,30 0,60" style="fill:#38405e;"></polygon>-->
<!--</svg>-->
<img src = "assets/img/arrow-down.png" class = "arrow-down-open" alt = "arrow-down" width = "60px"
height = "30px" />
</div>
<div class = "row">
<div class = "col-xs-12 col-sm-12 col-md-12 col-lg-12" (click) = "changeShowAgeSentiment()">
<div class = "widget clearfix" >
<div class = "widget-header">Sentiment By Age Range</div>
<div class = "widget-body-no-top-padding">
<div style = "min-height: 278px; width: 100%;">
<app-report-age-by-sentiment-chart-display
[episodeReport]="episodeReport"></app-report-age-by-sentiment-chart-display>
</div>
</div>
<div class = "widget-base"></div>
</div>
</div>
</div>
</div>

这里是否缺少一些基本的东西,或者我如何使组件检测到更改?

我的猜测是,您实际上并没有等到响应触发并返回值。 您只是在调用响应。尝试向服务呼叫添加.subscribe()

changeShowAgeSentiment(){
this.toggle.toggleReportAgeSentiment(!this.showHide).subscribe(res => this.showHide = res;
}

好的,所以我离开了一段时间,但现在我又回到了它,我弄清楚到底出了什么问题。

问题是我的每个组件都在创建它们订阅的服务的一个单独实例。当一个正在更新时,另一个看不到更新,因为它没有订阅同一实例。

为了解决这个问题,我将提供程序从每个服务移动到根组件,然后共享每个分支的服务量

最新更新