gpt4 book ai didi

Angular 5 HTML 在变量更改后不更新

转载 作者:行者123 更新时间:2023-12-04 13:43:39 25 4
gpt4 key购买 nike

我有一个奇怪的问题,当 Angular 组件变量更改时,我的 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 播放。变量是组件的一部分。

最佳答案

可能的原因

它看起来像 playing没有被捕获为 Angular 的变化检测器机制的一部分。

修复:你有几个选择

The first is to have setter and getter for the playing



函数始终作为变化检测器的一部分发挥着至关重要的作用,因此它确保您的变量变化得到反射(reflect)。

在 ts
get playingValue(){
return this.playing;
}

set playingValue(playing){
this.playing = playing;
}

html
Playing is {{ playingValue }}

The second option is to have 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;
});

关于Angular 5 HTML 在变量更改后不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52907539/

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