HTTP Module

  • Simplifies usage of the XHR and JSONP APIs
  • API conveniently matches RESTful verbs
  • Returns an observable
import { HttpClientModule } from '@angular/common/http';

Methods

  • request: performs any type of http request
  • get: performs a request with GET http method
  • post: performs a request with POST http method
  • put: performs a request with PUT http method
  • delete: performs a request with DELETE http method
  • patch: performs a request with PATCH http method
  • head: performs a request with HEAD http method
loadItems() {
 return this.http.get(BASE_URL);
}
createItem(item: Item) {
 return this.http.post(`${BASE_URL}`, item);
}
updateItem(item: Item) {
 return this.http.patch(`${BASE_URL}${item.id}`, item);
}
deleteItem(item: Item) {
 return this.http.delete(`${BASE_URL}${item.id}`);
}

Headers

  • HttpClient methods have an optional parameter which contains options for configuring the request
  • This options object has a headers property which is an HttpHeaders object
  • We can use the HttpHeaders object to set additional parameters like Content-Type
uploadFile(file: File, url: string) {
    const headers = new HttpHeaders().set('Content-Type', file.type);
    const options = {
        headers,
        reportProgress: true,
        observe: 'events',
        responseType: 'text' as 'text',
    };
    const req = new HttpRequest('PUT', url, file, options);
    return this.http.request(req);
}