Search code examples
angularangular-httpclient

Angular 6: How to get response status code


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);
      })
    }

Solution

  • 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 };
        });