Adding answer for versions of Angular >= 4.3 (including 15) with new HttpClient
that replaces http
In Angular versions 4.3 and later, the HttpClient module has been introduced, which is an improved version of the old Http module. It allows easier access to HTTP responses, including status code and headers.
Here's an example of how to use it:
In your module, import HttpClientModule:
import { HttpClientModule } from '@angular/common/http';
// Notice it is imported from @angular/common/http instead of @angular/http
In your component (if you just care of how to access the status check the console.logs):
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
private baseUrl = 'http://example.com/api/';
constructor(private http: HttpClient) {
this.activateUser('mailToken123');
}
activateUser(mailToken: string) {
this.http.get(
`${this.baseUrl}users/activate?mailToken=${mailToken}`,
{ observe: 'response' }
)
.subscribe(response => {
// Access the status code
console.log(response.status);
// Access a specific header
console.log(response.headers.get('X-Custom-Header'));
});
}
}
As noted in the comment by @Rbk, the observe: 'response' option passed in the request configuration object is key to getting the full response object, which includes the status code and headers.
Please be aware that not all headers are accessible due to the browser's same-origin policy and the server's Access-Control-Allow-Headers setting. You might not be able to retrieve certain headers unless both conditions are satisfied.
For more information, you can refer to the official Angular HttpClient documentation.
{observe:'response'}
is the deciding factor here and then you can return the full response accordingly.Without{observe:'response'}
,you won't get the full response,only the body data. – Mindoro