模型更改后角度视图未更新

时间:2017-10-21 17:02:12

标签: javascript angular typescript

我有一个简单的角度应用程序,可以使用下面的JavaScript Web Audio对象播放音频

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>

一切正常但视图在模型更改时不会更新

2 个答案:

答案 0 :(得分:1)

Angular会针对相同的Angular使用zonejs对浏览器事件进行更新绑定,这些使用会修补几个浏览器事件,并触发detectChanges方法以保持同步绑定。

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

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

答案 1 :(得分:-2)

  

以下是<form method='post' action='index.php'> <input type='submit' name='submit'> </form> <?php /* This is how the URL should look like // $url = "http://api.suredbits.com/nfl/v0/stats/wagner/bobby"; */ $url = "http://api.suredbits.com/nfl/v0/stats/"; if(isset($_POST['submit'])) { $names = array(); array_push($names, 'Bobby Wagner', 'Zach Brown', 'Mason Foster', 'Preston Smith', 'Josh Norman', 'Ryan Kerrigan', 'Earl Thomas', 'Richard Sherman', 'Chandler Jones', 'Marcus Peters'); foreach($names as $n) { $split_name = explode(" ", $n); $url .= $split_name[1] . '/' . $split_name[0]; //get json $data = loadFile($url); $json_data = json_decode($data, true); echo $n . ' Tackles: ' . $json_data[0]["defense"]["tackle"]; //reset url $url = "http://api.suredbits.com/nfl/v0/stats/"; } } function loadFile($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_URL, $url); $data = curl_exec($ch); curl_close($ch); return $data; } ?> 方法

&#13;
&#13;
setInterval
&#13;
&#13;
&#13;

但正如 @ user184994 所提到的那样,仅仅通过使用前端的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); } }可能会更加简单有效。

&#13;
&#13;
audio.currentTime
&#13;
&#13;
&#13;