首页 > 解决方案 > Angular 中的脚本和使用 A-Frame 的打字稿的问题

问题描述

我对一段 HTML 代码的脚本有角度问题,该代码使用 A-Frame 制作 3D 对象并与之交互。问题是您可以将声音作为 a-frame 的属性来播放,但是当尝试脚本或从打字稿中它不起作用并且一切都已尝试时。我希望他们能帮助我

<script>
AFRAME.registerComponent('play', {
  init: function () {
    console.log("entro al script play");
    var variable = document.querySelector('#yellow');
    this.variable.addEventListener('click' , function(){
      variable.components.sound.playSound();
    });
  }
});
AFRAME.registerComponent('stop', {
  init: function () {
    console.log("entro al script stop");
    var variable = document.querySelector('#yellow');
    this.variable.addEventListener('click' , function(){
      variable.components.sound.stopSound();
    });
  }
});
<a-box id="yellow" color="yellow" position="0 0 -5" sound="src:#bichota">
  <!-- Play -->
  <a-sphere color="green" radius="0.25" position="-1 1 0" play></a-sphere>
  <!-- Stop -->
  <a-sphere color="red" radius="0.25" position="1 1 0" stop></a-sphere>
</a-box>

在打字稿中,我收到此错误“类型'元素'上不存在属性'组件'”

var entity= document.querySelector('#yellow') ;
if(entity != null){
  console.log("enity" , entity);
  entity.components.sound.playSound();
}

标签: angulartypescriptaframe

解决方案


要在 Angular 中使用 aframe,最好遵循 Angular 的做法,而不是直接涉及 DOM 操作。

如需完整演示,您可以在 Github 上克隆我的演示项目。

app.component.html

<a-scene>
    <a-assets>
      <audio id="bichota" src="../assets/test.mp3" preload="auto"></audio>
    </a-assets>

    <a-box id="yellow" color="yellow" position="0 0 -5" sound="src:#bichota" #yellowBox>
      <a-sphere cursor="rayOrigin: mouse" color="green" radius="0.25" position="-1 1 0" (click)="playSound()"></a-sphere>
      <a-sphere cursor="rayOrigin: mouse" color="red" radius="0.25" position="1 1 0"  (click)="stopSound()"></a-sphere>
    </a-box>
</a-scene>
  • #yellowBox- 用于稍后在组件逻辑中引用它的角度
  • cursor="rayOrigin: mouse"- 用于通过鼠标单击元素。需要在 a-frame 元素中指定光标。有关详细信息,您可以阅读文档
  • (click)="xxxx()"- 用于绑定点击事件

app.component.ts

export class AppComponent {
  // refer to #yellowBox in the html
  @ViewChild('yellowBox') yellowBox!: ElementRef;
  
  playSound() {
    console.log("play")
    this.yellowBox.nativeElement.components.sound.playSound();
  }

  stopSound() {
    console.log("stop")
    this.yellowBox.nativeElement.components.sound.stopSound();
  }
}

推荐阅读