Fetch non-JSON data by specifying HttpClient responseType in Angular

Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 6 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.

egghead
egghead
~ a minute ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today