Angular 6: How to get response status code
Asked Answered
R

4

5

How do I get the service code? I try the code below, but it does not log anything.

In a service.ts file.

constructor(private http: HttpClient) { }

postForgotPass(email): Observable<Response> {

return this.http.post<Response>(envi.apiUrl +'/user/forgotpassword', {
  "email": email,
  "headers": headers,
  observe: 'response'

})
}

In my component.ts file

sendForgotPass() {
 return this.service.postForgotPass(this.emailFormControl.value)
    .subscribe(
      res => {
        console.log(res.status);
      })
    }
Rabble answered 19/3, 2019 at 17:47 Comment(2)
Have you tried Observable<HttpResponse>?Brazil
#46639654Flaunty
K
6

From Angular docs:

getConfigResponse(): Observable<HttpResponse<Config>> {
  return this.http.get<Config>(
    this.configUrl, { observe: 'response' });
}

Usage

this.configService.getConfigResponse()
    // resp is of type `HttpResponse<Config>`
    .subscribe(resp => {
      // display its headers
      const keys = resp.headers.keys();
      this.headers = keys.map(key =>
        `${key}: ${resp.headers.get(key)}`);

      // access the body directly, which is typed as `Config`.
      this.config = { ... resp.body };
    });
Knurly answered 19/3, 2019 at 17:56 Comment(0)
E
2

It is because non 2xx status codes are mapped to an error. You need to hook provide a handler for second parameter of subscribe(errors)

sendForgotPass() {
    return this.service.postForgotPass(this.emailFormControl.value)
        .subscribe(res => console.log(res.status), err => console.log('error', err.status))
    }
Evacuee answered 19/3, 2019 at 17:56 Comment(2)
This work, but even 2xx codes are logging as "error:200". Why is that?Rabble
Something else must be wrong. Try logging what is in err variable. Maybe some deserialisation or content type is wrong. Check network tab of browser that you get what you expect.Evacuee
T
0
if(response === undefined || response === ''  || response === null)
{  
    this.isStatusCode[i] = false;
}
Tank answered 30/12, 2020 at 9:57 Comment(0)
H
0

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

constructor( private httpClient: HttpClient){}

this.httpClient.get<any>(this.API_URL, {observe: 'response'})
        .subscribe({
          next: (res) => {
console.error(res.status)  // api status in header
console.error(res.body) // response from api
}
})`

{observe: 'response'} in get method gives full response object

Hippogriff answered 2/8, 2023 at 12:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.