【问题标题】:Angular 5 HTML not updating after variable change变量更改后Angular 5 HTML未更新
【发布时间】:2019-03-25 05:47:37
【问题描述】:

我遇到了一个奇怪的问题,我的 HTML 页面在 angular 组件变量更改时没有更新。按下按钮后,我进行网络加载并开始播放音频,如下所示:

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 上我有这个 sn-p:

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 变量是组件。

【问题讨论】:

标签: angular angular5


【解决方案1】:

可能的原因

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

修复:您有几个选择

首先是对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;
    });

【讨论】:

    【解决方案2】:

    你试过了吗:

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

    【讨论】:

      【解决方案3】:

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

      #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';
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-07
        • 2018-09-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多