使用Angular5 HttpClient读取本地.xml文件报错求助
Let's work through your issue step by step—there are a few small tweaks needed to get your local XML file loading correctly with Angular 5's HttpClient.
1. You're Missing the responseType Setting
By default, HttpClient expects to parse responses as JSON. When you load an XML file, this will throw an error because it can't parse XML into JSON. You need to explicitly set responseType: 'text' to tell Angular to return the raw text content instead.
2. Header Assignment Bug
In your code, you create a headers variable with the correct header, but then you pass the original, unmodified _headers to the request. That means your header setting isn't actually being used!
3. Verify Asset Path & Configuration
Make sure your data.xml is in the src/assets folder, and that your Angular CLI configuration (in angular.json) includes the assets directory so it gets copied to the build output.
Corrected Service Code
Here's the fixed version of your DataService:
import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; @Injectable() export class DataService { constructor(private _http: HttpClient) { } getFile() { // Set the appropriate Accept header to request XML const headers = new HttpHeaders().set('Accept', 'text/xml'); // Use the correct headers and specify responseType as text return this._http.get('/assets/data.xml', { headers: headers, responseType: 'text' }); } }
How to Use the Service in a Component
Once the service is fixed, you can call it in a component and even parse the XML if needed:
import { Component, OnInit } from '@angular/core'; import { DataService } from './data.service'; @Component({ selector: 'app-root', template: '<div *ngIf="xmlContent">{{xmlContent}}</div>' }) export class AppComponent implements OnInit { xmlContent: string; constructor(private dataService: DataService) {} ngOnInit() { this.dataService.getFile().subscribe( (response) => { this.xmlContent = response; // Optional: Parse the XML string into a DOM document const parser = new DOMParser(); const xmlDoc = parser.parseFromString(response, 'text/xml'); // Now you can work with the XML nodes, e.g. xmlDoc.getElementsByTagName('some-tag') }, (error) => { console.error('Failed to load XML:', error); // Handle error (e.g. show user message) } ); } }
Double-Check Your Angular CLI Assets Config
Ensure your angular.json has the assets folder listed so it's included in the build:
"architect": { "build": { "options": { "assets": [ "src/favicon.ico", "src/assets" ], // ... other options } } }
Common pitfalls to watch for:
- Using a relative path like
../assets/data.xmlcan cause issues depending on where the service is located—using the absolute path/assets/data.xmlis more reliable. - Forgetting
responseType: 'text'will almost always throw a JSON parsing error with XML files. - If you still get a 404 error, confirm the file path is correct and that the assets are being copied during the build.
内容的提问来源于stack exchange,提问作者raju

