6

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.

1

2 Answers 2

13

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

Sign up to request clarification or add additional context in comments.

2 Comments

can you fixed the header, i'm getting error "not json format"
@user2304483 maybe you are looking for somothing like this ?
5

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);

1 Comment

I can confirm that this approach works well to resolve this issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.