我有2个API请求,一个Get和一个Post,我想在屏幕上打印这些错误消息。您可以在此处查看GET请求的错误:
401 UNAUTHORIZED
{
"_status": "ERR",
"_error": {
"code": 401,
"message": "Please provide proper credentials"
}
}
您可以在此处查看POST请求的错误:
422 UNPROCESSABLE ENTITY
Append
{
"_status": "ERR",
"_error": {
"code": 422,
"message": "Duplicate licence plate found during insertion."
}
}
Remove
{
"_status": "ERR",
"_error": {
"code": 422,
"message": "Removal aborted. Licence plate not found in any or all of the given indexes."
}
}
401 UNAUTHORIZED
{
"_status": "ERR",
"_error": {
"code": 401,
"message": "Please provide proper credentials"
}
}
我的服务如下,但不打印这些消息。
getparkingDetails(): Observable<any>{
console.log(this.token);
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Bearer: ' + this.token,
}),
};
return this.httpclient.get<any>("https://socialpark.iti.gr:8005/parking_sites/management", httpOptions).pipe(
catchError(this.errorHandler));
}
errorHandler(error: any) {
//if (error == 404)
let errorMessage = '';
if (error.error instanceof ErrorEvent) {
// client-side error
errorMessage = `Error: ${error.error.message}`;
} else {
// server-side error
errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
}
window.alert(errorMessage);
return Observable.throw(errorMessage);
}
addparkingDetails(parkingSite: any): Observable<any>{
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Bearer: ' + this.token,
}),
};
return this.httpclient.post<any>(
"https://socialpark.iti.gr:8005/parking_sites/management/updates",
parkingSite,
httpOptions).pipe(
catchError(this.errorHandlerup));
}
errorHandlerup(error: any) {
let errorMessage = '';
if (error.error instanceof ErrorEvent) {
// client-side error
errorMessage = `Error: ${error.error.message}`;
} else {
// server-side error
errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
}
window.alert(errorMessage);
return Observable.throw(errorMessage);
}
我认为您需要在httpclient.get中使用observe:'response'
来读取完整的响应,如下所示:
getConfigResponse(): Observable<HttpResponse<Config>> {
return this.http.get<Config>(
this.configUrl, { observe: 'response' });
}
您可以在这里找到更多信息:https://angular.io/guide/http#reading-the-full-response