Sharing Top Content from the Angular-sphere.

The new Angular HttpClient API – Angular In Depth

The new Angular HttpClient API

☞ 

#Angular

  • We can do: – Rather than: – However if you’re still interested in the whole Response object you can observe for it: – // { observe: ‘response’ });Query parametersOne thing that might not be as intuitive is the way that it handles query parameters.
  • Type checking responsesThanks to TypeScript Generics you type HTTP method you’re calling and the response will get be of that same type: – interface LoginResponse { – accessToken: string; – accessExpiration: { – login: ‘foo’, – password: ‘bar’ – }).
  • As the Request and Response objects are immutable — which makes it easier to predict and test, we use the clone method to mutate the Response object.
  • In a file upload example it would be like that: – const req = new HttpRequest(‘POST’, ‘upload/file’, file, { – requestProgress: .
  • subscribe(event = { – if (event.type === HttpEventType.UploadProgress) { – console.log(event.total, event.loaded); – } – });Wrapping upThe HttpClient API is awesome.

The HttpClient API was introduced in the version 4.3.0. It is an evolution of the existing HTTP API and has it’s own package @angular/common/http. One of the most notable changes is that now the…

The HttpClient API was introduced in the version 4.3.0. It is an evolution of the existing HTTP API and has it’s own package @angular/common/http.

One of the most notable changes is that now the response object is a JSON by default, so there’s no need to parse it anymore. We can do:

Rather than:

However if you’re still interested in the whole Response object you can observe for it:

// { observe: ‘response’ });Query parametersOne thing that might not be as intuitive is the way that it handles query parameters. You can’t just really pass a Plain Old JavaScript Object (POJO) over and expect it to be assigned as a query parameter of the request like you would with any other option that can be passed to the options object of the GET call.

import { HttpParams } from ‘@angular/common/http’;const params = new HttpParams().set(‘q’, { params });This is a bit verbose. Luckily there’s already a pull request in place to enable the usage of object maps for parameters and headers of GET requests.

Type checking responsesThanks to TypeScript Generics you type HTTP method you’re calling and the response will get be of that same type:

interface LoginResponse {

accessToken: string;

accessExpiration: {

login: ‘foo’,

password: ‘bar’

}).subscribe(data = {

console.log(data.accessToken, non-JSON dataAlthough it’s the most common, sometimes you’ll deal with different sorts of data. This…

The new Angular HttpClient API – Angular In Depth