Angular 5 HTML 变量更改后未更新

Angular 5 HTML not updating after variable change

我遇到了一个奇怪的问题,当 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 不是真正的组件而是 window 变量的问题,但如果是这样的话,那么音频真的可以作为source变量是组件的一部分。

可能的原因

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

修复:您有几个选择

The first is to use setters and getters for the playing variable

函数作为变化检测器的一部分始终发挥着至关重要的作用,因此它确保您对变量的变化反映出来。

在*.ts

get playingValue(){
    return this.playing;
}

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

在*.html

Playing is {{ playingValue }}

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

你试过这个吗:

<button *ngIf="playing" style="width: 44px; height: 44px" (click)="onStopPressed()">
    <img src="/assets/stop.png" alt="Stop">
</button>

我遇到了类似的问题并通过以下方式修复了它:

#Inject ChangeDetectorRef to the constructor
 constructor(private changeDetectorRef: ChangeDetectorRef)

ngOnInit(): void {
  # get data or listen to changes
  # then 
  this.changeDetectorRef.detectChanges();
}

记得导入:

import { ChangeDetectorRef } from '@angular/core';