Picture of Brian Love wearing black against a dark wall in Portland, OR.

Brian Love

Angular HttpClient Response

Learn to obtain the full response of an HTTP request with Angular using HttpClient.

observe Reponse

This is a little thing I haven’t used before. You can easily obtain the full reponse of an HTTP request using the observe option with the HttpClient in Angular.

Here is an example:

@Injectable()
export class UserService {

  private readonly API_URL = 'https://reqres.in/api';

  constructor(private httpClient: HttpClient) { }

  createUser(user: User): Observable<User> {
    return this.httpClient.post<User>(`${this.API_URL}/users`, user, {
      observe: 'response'
    });
  }

}

By specifying the response string constant Angular will return the HttpResponse object:

{
  "headers": {
    "normalizedNames": [],
    "lazyUpdate": null
  },
  "status": 201,
  "statusText": "OK",
  "url": "https://reqres.in/api/users",
  "ok": true,
  "type": 4,
  "body": {
    "id": 1,
    "firstName": "Brian",
    "lastName": "Love",
    "createdAt": "2018-08-31T02:28:09.162Z"
  }
}

Check out the following stackblitz showing the use of observing the response:

observe Events

Additionally, you can observe the HTTP ready status events of the request using the events string constant:

@Injectable()
export class UserService {

  private readonly API_URL = 'https://reqres.in/api';

  constructor(private httpClient: HttpClient) { }

  createUser(user: User): Observable<User> {
    return this.httpClient.post<User>(`${this.API_URL}/users`, user, {
      observe: 'events',
      reportProgress: true
    });
  }

}

Note:

You may need to throttle your network requests to see the progress.

At first, you should see the type set to 0:

{
  "type": 0
}

This indicates that the request has not been sent yet. Next, you should see the opened event:

{
  "type": 1,
  "loaded": 46,
  "total": 46
}

Finally, the type should be 4 - DONE:

{
  "headers": {
    "normalizedNames": [],
    "lazyUpdate": null
  },
  "status": 201,
  "statusText": "OK",
  "url": "https://reqres.in/api/users",
  "ok": true,
  "type": 4,
  "body": {
    "id": 1,
    "firstName": "Brian",
    "lastName": "Love",
    "createdAt": "2018-08-31T02:45:28.882Z"
  }
}

Check it out: