Angular 中的脚本和使用 A-Frame 的打字稿的问题

Problems with a script in Angular and typescript using A-Frame

我在 angular 中遇到了一段 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>

在打字稿中我得到这个错误“属性 'components' 在类型 'Element' 上不存在”

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

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

如需完整演示,您可以克隆 my demo project on 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 - angular 稍后在组件逻辑中引用它
  • cursor="rayOrigin: mouse" - 用于启用鼠标点击元素。需要在 a-frame 元素中指定光标。详情可以阅读the doc.
  • (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();
  }
}