Attempting to send an HTTP request to the Spring REST API, which returns a string value ('success' or 'fail'). However, I am uncertain of how to specify the response type as a string value when making the call to the API. The error message states "Backend returned code 200, body was: [object Object]".
The Angular code snippet is as follows:
order.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { ProductSearch } from '../_models/product-search';
import { ProductView } from '../_models/product-view';
import { Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { ErrorHandlerService } from './error-handler.service';
import { Category } from '../_models/category';
@Injectable({
providedIn: 'root'
})
export class OrderService {
constructor(private http: HttpClient, private errorHandlerService: ErrorHandlerService) { }
addToCart(productId: number, quantity: number): Observable<any> {
const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
console.log("--------order.service.ts----------addToCart()-------productId:"+productId+":------quantity:"+quantity);
return this.http.post<any>('http://localhost:8080/order/addtocart',
{ dealerId: 13, createdBy: "-1", productId: productId, quantity: quantity},
{headers: headers})
.pipe(catchError(this.errorHandlerService.handleError));
}
}
error-handler.service.ts
import { Injectable } from '@angular/core';
import { HttpErrorResponse, HttpResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class ErrorHandlerService {
constructor() { }
public handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
// return an observable with a user-facing error message
return throwError(
'Something bad happened; please try again later.');
};
}