我使用angular4作为仪表板,当用户在单独的组件中单击div时,我会隐藏一个div。我已经创建了一个带有布尔值observable的服务,但是当我点击按钮隐藏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>
我是否缺少基本的东西,或者如何让组件检测到变化?
答案 0 :(得分:0)
我的猜测是你实际上并没有等到响应触发并返回值。你只是在回应。尝试在服务电话中添加.subscribe()
。
changeShowAgeSentiment(){
this.toggle.toggleReportAgeSentiment(!this.showHide).subscribe(res => this.showHide = res;
}
答案 1 :(得分:0)
好的,所以我离开了一段时间,但我现在回到它,我想出了究竟出了什么问题。
问题是我的每个组件都在创建他们订阅的服务的单独实例。当一个人正在更新时,其他人没有看到更新,因为它没有订阅同一个实例。
为了解决这个问题,我将每个服务的提供者移动到根组件,然后分享每个分支的服务金额