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

标签 angular angular5

我有一个奇怪的问题,当 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/

相关文章:

Angular4 componentInstance 和 debugElement.componentInstance 的区别

Angular 5 - 在运行时动态加载模块(编译时未知)

带防护的 Angular 5 无组件路由无法命中重定向

angular - 将子组件表单绑定(bind)到父组件表单

html - 如何使用 Angular 2/Typescript 限制输入字段中的特殊字符

javascript - 如何在 ng-template 中使用响应式表单

javascript - Angular,如何对窗口调整大小事件使用react

angular - 在 Angular 2 中订阅主/详细信息示例中的子路由更改

javascript - 线性模式在具有单独组件的 mat-h​​orizo​​ntal-stepper 中不起作用

angular - Ng4LoadingSpinner 5 秒后超时