我遇到一个奇怪的问题,当角度分量变量更改时,我的HTML页面没有更新。按下按钮后,我会加载网络并开始播放音频,如下所示:
onPreviewPressed(media: Media): void {
if (this.playing) {
this.playing = false;
this.source.stop();
}
this.loading = true;
this.service.downloadAudio(this.gender, this.style, this.ageRange, media).subscribe(abuf => {
this.context.decodeAudioData(abuf, buffer => {
this.source.buffer = buffer;
this.playing = true;
console.info(`Playing is ${this.playing}`);
this.source.start(0);
}, y => {
console.info('Error: ' + y);
});
this.loading = false;
}, () => {
this.loading = false;
});
}
然后在我的HTML上有以下代码段:
Playing is {{ playing }}
<button [hidden]="!playing" style="width: 44px; height: 44px" (click)="onStopPressed()">
<img src="/assets/stop.png" alt="Stop">
</button>
当我单击按钮时,音频会正确下载并开始播放,并且在控制台中看到Playing is true
,但HTML继续显示为false,并且不显示按钮。
我认为这可能不是this
的问题,而是窗口变量,但如果是这种情况,那么音频确实可以作为source
变量播放是组件的一部分。
答案 0 :(得分:1)
看来playing
没有被捕获为Angular的变更检测器机制的一部分。
第一个方法是为
playing
设置setter和getter方法
功能始终是变更检测器的重要组成部分,因此可以确保您的变量更改能够得到反映。
get playingValue(){
return this.playing;
}
set playingValue(playing){
this.playing = playing;
}
Playing is {{ playingValue }}
第二个选项是设置setTimeout
this.service.downloadAudio(this.gender, this.style, this.ageRange, media).subscribe(abuf => {
this.context.decodeAudioData(abuf, buffer => {
this.source.buffer = buffer;
setTimeout(()=>this.playing = true); //setTimeout
console.info(`Playing is ${this.playing}`);
this.source.start(0);
}, y => {
console.info('Error: ' + y);
});
this.loading = false;
}, () => {
this.loading = false;
});
答案 1 :(得分:0)
您尝试过吗:
<button *ngIf="playing" style="width: 44px; height: 44px" (click)="onStopPressed()">
<img src="/assets/stop.png" alt="Stop">
</button>