I get an error when trying to call a service from Angular 8 app. Here is the service:
const httpOptionsPlain = {
headers: new HttpHeaders({ 'Accept': 'text/plain',
'Content-Type': 'text/plain'
})
};
@Injectable()
export class TripService {
public getTripNameById(tripId: number): Observable<any> {
return this.http.get<any>(`${this.baseUrl}/Trips/Trip/Name/${tripId}`, httpOptionsPlain);
}
And here is the Java rest api (works fine when calling from the browser):
@GET
@Path("Trip/Name/{fundId}")
@Produces("text/plain")
public String getTripNameById(@PathParam("tripId") Integer tripId) {
return myDao.getNameById(tripId);
}
I'm getting the error in the chrome console:
error: {error: SyntaxError: Unexpected token A in JSON at position 0 at JSON.parse () at XMLHtt…, text: "AAA BBB CCC"} headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ} message: "Http failure during parsing for http://localhost:8080/... name: "HttpErrorResponse"
I'm sending plain text so I'm not why the service try to parse json.
Please try
const httpOptionsPlain = {
headers: new HttpHeaders({
'Accept': 'text/plain',
'Content-Type': 'text/plain'
}),
'responseType': 'text'
};
@Injectable()
export class TripService {
public getTripNameById(tripId: number): Observable<string> {
return this.http.get<string>(`${this.baseUrl}/Trips/Trip/Name/${tripId}`, httpOptionsPlain);
}
I've just added '
to the responseType
HttpClient by default converts response to be response.json(). In case you are API returns non-json response, you have to specify that
this.http.get(url, {responseType: 'text'}).
In your code make it non-generic by removing <string>
return type for it to work -
return this.http.get(`${this.baseUrl}/Trips/Trip/Name/${tripId}`, httpOptionsPlain);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With