It appears that my client is unable to capture the response data from the server and display it.
Below is the code for my component:
export class MyComponent implements OnInit {
data: string;
constructor(private myService: MyService) {}
ngOnInit() {}
testCall() {
this.myService.getData().subscribe(data => this.data = data);
console.log("Data: " + this.data);
}
}
The service code:
@Injectable()
export class MyService {
private url = 'http://localhost:5000/myproj/api/test';
constructor(private http: HttpClient) { }
// Get data from the server
getData(): Observable<string> {
console.log("in getData() method");
return this.http.get<string>(this.url)
.pipe(
catchError(this.handleError) // then handle the error
);
}
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
console.error('An error occurred:', error.error.message);
} else {
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
return new ErrorObservable('Something went wrong; please try again later.');
};
}
Upon sending a request to the server, the response body contains the data with a status code of 200 shown in developer tools in Internet Explorer:
https://i.sstatic.net/RuiVo.png
However, when calling the getData()
service method, Angular client is invoking the catchError()
method resulting in the message:
Backend returned code 200, body was: [object Object]
ERROR Something went wrong; please try again later.
I am puzzled as to why the server responds with status 200 but the Angular client triggers the catchError()
method?
EDIT:
Below is the API code on the server side:
@RequestMapping(value = "/test", method = RequestMethod.GET, produces = "text/plain")
public String testApi(HttpServletRequest request) {
System.out.println("in /test");
String response = "my response";
return response;
}