Angular 2 4 HttpClient. POST request - how to get status code

user7337867 picture user7337867 · Oct 25, 2017 · Viewed 9k times · Source

How can I get status code of response POST request? My service method return:

return this.httpClient.post(url, body, {observe: 'response'})
            .catch(HandleError.handleErrorClient);

In my component I call this method and subscribe:

    .subscribe(
        res => {
            console.log(res);
            console.log(JSON.stringify(res));
            this.responseStatus = res.status;
            console.log(this.responseStatus);
        },
        err => {
            this.responseStatus = err.status;
        });

But in browser console there is nothing - but when the request contains a error then this.responseStatus = err.status return correct status code, but res.status or res doesn't contain status code, only response body.

EDIT:

Component:

responseStatus: number;

loginUser() {
    this.loginData = this.loginForm.getRawValue();
    this.userLoginService.loginUser(this.loginData)
        .subscribe(
            res => {
                console.log('bla bla');
                this.responseStatus = res.status;
            },
            err => {
                console.log(err.status); //401
                console.log(err.error.error); //undefined
                console.log(JSON.parse(err.error).error); //unauthorized
                this.responseStatus = err.status;
            });
}

Service:

import {Http} from "@angular/http";
import {HttpClient} from '@angular/common/http';

...

    constructor(private http: Http, private httpClient: HttpClient) {
    }


    loginUser(loginData: LoginForm) {
        return this.httpClient.post(this.loginURL, loginData, {observe: 'response'})
            .catch(HandleError.handleError);
    }

handle-error.ts

export class HandleError {

    static handleError(error: Response | any) {
        let errMsg: string;
        if (error instanceof Response) {
            const body = error.json() || '';
            const err = body.error || JSON.stringify(body);
            errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        } else {
            errMsg = error.message ? error.message : error.toString();
        }
        console.error(errMsg);
        return Observable.throw(error);
    }
}

POST: /api/login enter image description here I'm login correctly, but nothing more... I expected in browser console: console.log('bla bla');. With Http there isn't problems.

Answer