'Angular http post with HttpResponse
In my angular service (EmployeeService) I have the following:
httpPostOption: { headers: any; observe: any; } = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
}),
observe: 'response'
};
createEmployeeWithHeaders(employee: IEmployee): Observable<HttpEvent<IEmployee>> {
return this.http
.post<IEmployee>(
this.apiURL + '/employee',
JSON.stringify(employee),
this.httpPostOption
)
.pipe(retry(1), catchError(this.handleError));
}
The problem is with the response (of type HttpEvent) - the code in the calling component is like this:
let post = {'firstName': this.currentFirstName(),
'lastName': this.currentLastName(),
'email': this.currentEmail(),
'phone': this.currentPhone(),
'password': this.currentPassword()} as IEmployee
this.employeeService.createEmployeeWithHeaders(post).subscribe((response: HttpEvent<IEmployee>) => {
console.log('Employee created', response)
The console.log shows both data and headers from the server but I´m unable to access response.ok or response.statusText like I can with a HttpResponse which I can get from a http.get-call to the server.
I´ve tried to change the method to this:
createEmployeeWithHeaders(employee: IEmployee): Observable<HttpResponse<IEmployee>> {
return this.http
.post<IEmployee>(
this.apiURL + '/employee',
JSON.stringify(employee),
this.httpPostOption
)
.pipe(retry(1), catchError(this.handleError));
}
But changing the Observable to HttpReponse instead of HttpEvent cause an error like:
Type 'HttpSentEvent' is missing the following properties from type 'HttpResponse': body, clone, headers, status, and 3 more
Any suggestions on how to get the entire response as a HttpReponse?
Regards Kaare
Solution 1:[1]
If I replace: this.httpPostOption in
createEmployeeWithHeaders(employee: IEmployee): Observable<HttpEvent<IEmployee>> {
return this.http
.post<IEmployee>(
this.apiURL + '/employee',
JSON.stringify(employee),
this.httpPostOption
)
.pipe(retry(1), catchError(this.handleError));
}
with: {headers: new HttpHeaders({'Content-Type': 'application/json'}),observe: 'response'} in
createCustomer(customer: ICustomer): Observable<HttpResponse<ICustomer>> {
return this.http
.post<ICustomer>(
this.apiURL + '/customer/',
JSON.stringify(customer),
{headers: new HttpHeaders({'Content-Type': 'application/json'}),observe: 'response'}
).pipe(catchError(this.handleError));
}
It works - though I cannot see what the difference is
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | K.M.Rasmussen |