I get the error mentioned above each time that I try to call a string from my Spring API on Angular 11. I understand that this error means that I am basically trying to parse a JSON with incorrect syntax , but I am sending a string from my API to Angular and taking that string and then assigning (or subscribing) it to a string variable. I don't know where the JSON.parse() is taking place and I would like to disable it or avoid the error all together.
Here is my Angular 11 Code.
Block.services.ts
public getBlockHash(height:Number): Observable<string> {
return this.http.get<string>(`${this.apiServerUrl}/blockhash/${height}`)
}
block.component.ts
public getBlockHash(height:Number){
let result = this.service.getBlockHash(height)
console.log(result)
result.subscribe((data)=> this.blockHash = data)
}
And this is the Spring code.
block.controller
@GetMapping("/blockhash/{height}")
public String getBlockHash(@PathVariable int height) {
String hashCode = service.getBlockHash(height);
return hashCode;
}
blockservice.java
public String getBlockHash(int number) {
String result = RPCRequest.rpcPost(GETBLOCKHASH, number);
BaseEntity<String> baseEntity = JSONObject.parseObject(result,
new TypeReference<BaseEntity<String>>() {
});
return baseEntity.getResult();
}
You can set an option to avoid parsing the response to the JSON format (the default) and get it as plain text.
Try change the Angular Http call by adding the option: {responseType: 'text'}
; like this:
public getBlockHash(height:Number): Observable<string> {
return this.http.get(`${this.apiServerUrl}/blockhash/${height}`, {
responseType: 'text'
})
}