【问题标题】:Angular View not updating after model changes模型更改后角度视图不更新
【发布时间】:2018-04-02 14:36:34
【问题描述】:

我有一个简单的 Angular 应用程序来使用下面的 JavaScript 网络音频对象播放音频

app.component.ts

export class AppComponent {
  title = 'media player';
  audio;
  currentTime: number;

  constructor() {
    this.audio = new Audio();
    this.audio.src = './Music/demo2.MP3';
    this.audio.play();
    this.currentTime = this.audio.currentTime;
  }
}

和 app.component.ts

<h4>{{ currentTime }}</h4>

一切正常,但视图不会随着模型的变化而更新

【问题讨论】:

  • 你能不绑定到audio.currentTime吗?
  • 这是因为this.currentTime = this.audio.currentTime;这一行只在组件加载时运行一次。您需要确保该行每秒更新一次。或者@user184994 方法也可以工作。
  • @PraveenM 是的,我明白this.currentTime = this.audio.currentTime; 只运行一次。请问你知道如何使这些工作。
  • @OchuiPrincewill 你可以使用 JavaScript setInterval 函数每秒更新一次值。

标签: javascript angular typescript


【解决方案1】:

Angular 确实更新了浏览器事件的绑定,因为 Angular 使用 zonejs 猴子修补了几个浏览器事件,并触发 detectChanges 方法以保持绑定同步。

在这种情况下,Angular 不会更新绑定,因为Audio API 事件不会通过 zonejs 进行猴子补丁。对于这种情况,您必须手动运行更改检测以手动更新绑定。您可以使用audio API 的ontimeupdate 事件处理程序。

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

export class AppComponent {
  title = 'media player';
  audio;
  currentTime: number;

  constructor(private cd: ChangeDetectorRef ) {
  }
  ngOnInit(){
     this.audio = new Audio();
     this.audio.src = './Music/demo2.MP3';
     this.audio.play();
     //this will make sure to update when time updates.
     this.audio.ontimeupdate = (event) => {
        this.currentTime = this.audio.currentTime;
        this.cd.detectChanges();
     }
  }
}

【讨论】:

    【解决方案2】:

    这是setInterval 方法

    export class AppComponent {
      title: string = 'media player';
      audio: Audio;
      currentTime: number;
    
      constructor() {
        this.audio = new Audio();
        this.audio.src = './Music/demo2.MP3';
        this.audio.play();
        this.currentTime = this.audio.currentTime;
      }
      
       ngOnInit() {
         setInterval(() => {
          this.currentTime = this.audio.currentTime;
        }, 1000);
       }
    }

    但正如 @user184994 所提到的,仅在前端使用 audio.currentTime 可能是更简单有效的方法。

    &lt;h4&gt;{{ audio.currentTime }}&lt;/h4&gt;

    【讨论】:

    • 我认为setInterval 是一种代码味道。它使代码和测试复杂化,并且在 OP 试图完成时似乎没有必要。
    • @stealththeninja OP 的问题是currentTime 在播放音频时不会不断更新,这是我会考虑的一种方法。这就是为什么我提到使用audio.currentTime 本身,正如我假设的那样,它会随着音频的播放而更新,非常稳定和有效。
    • 最好使用事件监听器而不是setInterval,媒体元素有timeupdate事件:developer.mozilla.org/en-US/docs/Web/Events/timeupdate
    • @stealththeninja 是的,我在回答中使用了相同的内容:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-23
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    • 2017-08-14
    相关资源
    最近更新 更多