Fetch API (function)
The most useful, high-level part of the Fetch API is the fetch()
function. In its simplest form it takes a URL and returns a promise that resolves to the response. The response is captured as a Response
object.
// Fetch sample
saveCourse(id: number, changes: any): any {
return of(fetch(`/api/courses/${id}`)
.then(result => {
console.log(result);
})
.catch(err => {
console.error(err);
}), {
method: 'PUT',
body: JSON.stringify(changes),
headers: {
'content-type': 'application/json'
}
});
}
Submitting some parameters, it would look like this:
fetch("http://www.example.org/submit.php", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: "firstName=Nikhil&favColor=blue&password=easytoguess"
}).then(function(res) {
if (res.ok) {
alert("Perfect! Your settings are saved.");
} else if (res.status == 401) {
alert("Oops! You are not authorized.");
}
}, function(e) {
alert("Error submitting form!");
});
For more information about the fetch method, please check this link https://hacks.mozilla.org/2015/03/this-api-is-so-fetching/
Last updated
Was this helpful?