1

I will like to read an XML file from found in src/assets/test.xml. I have a component found in src/app/app.component.ts as so:

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Component({
    selector: 'app-root',
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.css']
})
export class HomeComponent {
    constructor(private router: Router, private httpClient: HttpClient) {
        this.getProducts();
    }


    getProducts() {
        const headers = new HttpHeaders();
        headers.set('Content-Type', 'text/xml');

        this.httpClient
            .get('assets/test.xml', { headers, responseType: 'text' })
            .subscribe(output => console.log(output));
    }
}

Inside the app.module.ts I have imported the HttpClientModule as required and the only error message I receive is:

{
    body: {error: "Collection 'test' not found"},
    headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ},
    status: 404,
    statusText: "Not Found",
    url: "assets/test.xml"
}

I tried with other assets in the assets folder but still without any success. Can anyone help me out please?

macvag
  • 401
  • 4
  • 11
cross19xx
  • 3,170
  • 1
  • 25
  • 40
  • (1) You are making an HTTP GET request to your server, when you actually want to read a local file --> 404 route not found. (2) I don't think you can read a local file, even just XML, from a browser. Browsers don't allow JS to access the local file system, for security reasons. – Jeremy Thille Apr 03 '19 at 14:08
  • Okay. Do you have any recommendation on how to go about this? – cross19xx Apr 03 '19 at 14:09
  • The file has to be hosted and served ( = sent by your server). You can't simply read it locally from a browser. https://stackoverflow.com/questions/14106501/read-xml-file-using-javascript-from-a-local-folder – Jeremy Thille Apr 03 '19 at 14:10
  • Thank you very much for your answer. I don't seem to understand it. Can you take some time to properly explain it to me? – cross19xx Apr 03 '19 at 14:19
  • Hmmm, it's a loooong topic. I suggest you follow a few tutorials on this subject. Google "serve a file + [the language you use for your server] (Java, PHP, Python, etc.)" But the general idea is that Javascript in a browser does not have access to the file system, so it can't read local files. Servers, on the other hand, can. So you have to make a HTTP request to your server, and the server must read the file and send it back as a response. – Jeremy Thille Apr 03 '19 at 14:38
  • I think I understand you. Browsers can't read files from a server as if they were accessing their local file, they only make a request and the server (who can read the files) return a response. – cross19xx Apr 03 '19 at 14:50

0 Answers0