我正在调用 api 并在另一个函数 tapplace 中使用文件类型变量,但该函数有时会运行,有时无法帮助理解和清除问题我猜这是因为获取 API 调用的异步行为
var query = window.location.search.replace("?", "");
var slug_url = query.split("?id=");
slug_url = `${slug_url}`.replace("id=", "");
let filetype = '';
fetch("https://api.morkshub.xyz/api/get_node/" + slug_url)
.then(response => response.json())
.then(data => {
console.log(data)
data.data.map((obj) => {
var newAssets = obj.assets;
newAssets.map((newObj) => {
if (newObj.type == "content") {
const gltfUrl = `url(${ApiAssetUrl + newObj.assets})`;
content = ApiAssetUrl + newObj.assets;
if(gltfUrl.includes(".glb")){
filetype = 'model'
}else if(gltfUrl.includes(".jpg") || gltfUrl.includes(".png") || gltfUrl.includes(".png")){
filetype = 'image';
}else if(gltfUrl.includes(".mp4") || gltfUrl.includes(".m4v")){
filetype = 'video'
}
console.log(filetype)
tapplace();
}
});
});
});
async function tapplace(){
const tapPlaceCursorComponent = {
init() {
console.log("hellooooooo" , filetype)
let model;
if(filetype == "image"){
model = document.getElementById('entityimage');
} else if(filetype == "video"){
model = document.getElementById('entityvideo');
} else{
model = document.getElementById('model');
}
this.model = model;
this.raycaster = new THREE.Raycaster();
this.camera = document.getElementById('camera');
this.threeCamera = this.camera.getObject3D('camera');
this.ground = document.getElementById('ground');
this.cursor = document.getElementById('cursor');
let hasPlacedModel = false;
// 2D coordinates of the raycast origin, in normalized device coordinates (NDC)---X and Y
// components should be between -1 and 1. Here we want the cursor in the center of the screen.
this.rayOrigin = new THREE.Vector2(0, 0);
this.cursorLocation = new THREE.Vector3(0, 0, 0);
this.el.sceneEl.addEventListener('click', (event) => {
if (hasPlacedModel !== true) {
hasPlacedModel = true;
this.model.setAttribute('position', this.el.object3D.position);
this.model.setAttribute('visible', 'true');
this.model.play();
hasPlacedModel = true;
// Remove ghosted model from scene after model is placed
this.cursor.parentNode.removeChild(this.cursor);
// Add raycaster to camera
this.camera.setAttribute('raycaster', 'objects: .cantap');
}
});
},
tick() {
// Raycast from camera to 'ground'
this.raycaster.setFromCamera(this.rayOrigin, this.threeCamera);
const intersects = this.raycaster.intersectObject(this.ground.object3D, true);
if (intersects.length > 0) {
const [intersect] = intersects;
this.cursorLocation = intersect.point;
}
this.el.object3D.position.y = 0.1;
this.el.object3D.position.lerp(this.cursorLocation, 0.4);
this.el.object3D.rotation.y = this.threeCamera.rotation.y;
},
};
AFRAME.registerComponent('tap-place-cursor', tapPlaceCursorComponent);
}
我想从 api 设置文件类型变量的值,并想在下面的 tapplacecursor 组件中使用它,但该功能无法正常工作