Fetch non-JSON data by specifying HttpClient responseType in Angular

Share this video with your friends

Send Tweet
Published 5 years ago
Updated 4 years ago

By default the new Angular Http client (introduced in v4.3.1) uses JSON as the data format for communicating with the backend API. However, there might be situations where you may want to use some other format, like text/plain for fetching a CSV file. Using the responseType property this can be achieved quite easily.

In this people service that gets used by the app component to fetch the data, we issue an HTTP call to this endpoint here. I'm serving this project with Angular CLI so therefore here I have an asset, an asset folder, a people JSON file which gets here rendered and served by the integrated Web server.

Now, with new HTTP client which we are using here which has been introduced in Angular version 4.3.1, by default the response sent from the server gets interpreted as JSON format, so there's no more need as was the case before to basically parse this response and map it JSON, which is a nice addition of this new HTTP client.

What happens for instance if we have another endpoint, let's say people TXT which returns the data as the text format which is not JSON obviously? Let's give it a try. If I change this here to the TXT endpoint and then click the fetch people button, nothing happens.

If we open up the Chrome dev tools, we can actually see that the call is being issued, so we get also a successful response from the server, but Angular itself doesn't actually show us to the user interface. The problem is because, behind the scenes, an error happens, which in this specific case, we are not handling here. We get no error actually.

In order to resolve this, we can tell Angular what we expect as a response type. The second parameter which we can pass to that get function, we specify there the response type which in this case is simply text. If we now invoke the call again, we can see the text gets properly displayed here our UI.