Strategies for Handling Asynchronous Information
Learn how to fetch data from HTTP using observables and working with the built-in Angular HTTP client.
We'll cover the following...
Before we dive deeper into describing the Angular built-in HTTP client and how to use it to communicate with servers, let’s talk about native HTTP implementations first. Currently, if we want to communicate with a server over HTTP using JavaScript, we can use the fetch API. It contains all the necessary methods to connect with a server and start exchanging data. We can see an example of how to fetch data in the following code:
fetch(url).then(response => {return response.ok ? response.text() : '';}).then(result => {if (result) {console.log(result);} else {console.error('An error has occured');}});
Although the fetch API is promise-based, the promise that returns is not rejected in case of error. Instead, the request is unsuccessful when the ok
property is not present in the response
object. If the request to the remote URL completes, we can use the text()
method of the response
object to return the response text inside a new promise on ...