Angular 9.1 + Babylon 4.1加载GLTF模型出现404错误求助
Hey there! Let's break down why your GLTF model is hitting a 404 even though the path seems correct—this is a common gotcha with Angular's resource handling, so let's fix it step by step.
First: Angular Doesn't Automatically Bundle Files in TS Directories
Angular has strict rules about which files get included in your final build. By default, it only treats files in the src/assets folder (or directories explicitly listed in your angular.json assets config) as static resources.
Even if you placed bmw.gltf in the same folder as your service's TS file, Angular won't copy it to the dist folder during build. That's why the browser can't find it—when you use ./bmw.gltf, it's trying to fetch from your app's root URL (e.g., http://localhost:4200/bmw.gltf), where the file doesn't exist.
(Your test PNG might have worked if it was accidentally included via another Angular feature, but GLTF files aren't handled the same way by default.)
Fix 1: Move the Model to the Assets Folder (Easiest Option)
- Create a
modelssubfolder insidesrc/assets(e.g.,src/assets/models/). - Copy your entire GLTF package (
.gltf,.bin, and any texture files) into this folder. - Update your
SceneLoaderpath to use the absolute asset path:BABYLON.SceneLoader.Append("/assets/models/", "bmw.gltf", this.scene, function (scene) { // Your post-load logic here });
Fix 2: Add Your TS Directory to Angular's Assets Config
If you don't want to move the model, tell Angular to bundle files from your service's directory:
- Open
angular.jsonin your project root. - Find the
assetsarray underprojects -> [your-project-name] -> architect -> build -> options. - Add an entry for your service's directory:
{ "glob": "**/*", "input": "src/app/path-to-your-service-directory", // Replace with your actual folder path "output": "./assets/models" // Where the files will live in the dist folder } - Now you can access the model using the same
/assets/models/bmw.gltfpath as in Fix 1.
Second: Double-Check Your Path Syntax
Avoid using relative paths like ./ here—they're relative to the browser's current URL, not your TS file's location. Using an absolute path starting with / ensures you're pointing directly to the bundled asset.
Third: Verify the Model is Actually Bundled
Run ng build and check the dist/[your-project-name]/assets/models folder—you should see bmw.gltf (and any associated files) there. If not, double-check your assets config or folder structure.
Quick Check for Loader Import
You already imported 'babylonjs-loaders' correctly, but just to be safe, make sure your babylonjs-loaders package version matches your babylonjs version (both 4.1.x). Mismatched versions can cause weird issues, but your 404 error is almost certainly a resource path problem, not a loader import issue.
Once you fix the asset path, your GLTF model should load without the 404!
内容的提问来源于stack exchange,提问作者Akki619

