变量更改后,角度5 HTML未更新 [英] Angular 5 HTML not updating after variable change

查看:30
本文介绍了变量更改后,角度5 HTML未更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个奇怪的问题,当角度分量变量更改时,我的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未以角度捕获为更改检测器机制的一部分。

修复:您有几个选择

第一个是为playing变量使用setter和getter

函数始终作为更改检测器的一部分发挥重要作用,因此它可确保您在变量中所做的更改得到反映。

*.ts中的

get playingValue(){
    return this.playing;
}

set playingValue(playing){
    this.playing = playing;
}
*.html中的

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;
    });

这篇关于变量更改后,角度5 HTML未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆