I'm trying to solve another Angular problem - can you help me? In my component I have a login function - like this:
onLogin() {
if (this.loginForm.valid) {
const email = this.loginForm.get(['email']).value;
const password = this.loginForm.get(['password']).value;
this.ls.login(email, password).subscribe(
result => {
this.saveToken(result);
},
error => {
this.errorMessage = error;
this.loginForm.reset();
}
);
} else {
this.updateErrorMessage();
}
}
My service function looks like that:
login(email: string, password: string): Observable<string> {
const apiUrl = environment.apiHostLumen + '/admin/login?email=' + email + '&password=' + password;
const headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
const options = new RequestOptions({ headers: headers });
return this.http.get(apiUrl, options).pipe(
retry(3),
map(res => res.json()),
map(data => {
return data.token;
}),
catchError(this.ehs.handleError('login'))
);
}
Now I have implemented the function for error handling exactly as described in the documentation of Angular. I have outsourced the feature and it looks like that:
handleError<T> (operation = 'operation', result?: T) {
return (error: HttpErrorResponse): Observable<T> => {
const userMessage = error.message;
return throwError(userMessage);
};
}
But how it's possible to access the body of the API response? error.message is always undefined. I only have access to the status code and url. How can I access the response body if the API returns an error code different from 200 ?
Thanks a lot
error.json()is not available for typeHttpErrorResponse