Communicating data over HTTP
Before we dive into describing the Angular 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 JavaScript-native fetch
API. It contains all the necessary methods to connect with a server and exchange data.
You 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 occurred');
}
});
Although the fetch
API is promise-based, the promise it returns is not rejected if there is an error. Instead, the request is unsuccessful when the ok
property is not in the response
object.
If the request to the remote URL is completed, we can use the text()
method...