Get string value from backend in Angular 8

Viewed 3501

I create an API to get the country of the user from Spring boot. The code snippets are displayed below.

SearchRepository.java

    @Query("SELECT u.country FROM Users u WHERE u.email = :email")
        String findCountryByEmail(@Param("email") String email);

Controller.java

@Autowired                                                                                  
    private SearchRepository user;

    @GetMapping("/country/{email}")
    public String getCountry(@PathVariable("email") String email) {
        return user.findCountryByEmail(email);
    }

This API returns the country as a string. I want to display this country on my angular frontend. I created the following codes in angular to achieve this task.

 DataService.ts  
 getCountry(email: string) {
        return this.http.get<string>(`${API_URL}/country/${email}`);
      }
profile.ts
getCountry(myEmail: string) {
   this.service.getCountry(myEmail)
        .subscribe(
          data => this.country = data
        );
  }

I used the above getcountry method inside the ngOninit to initialize the country of the user when loading the profile. But the country field remained empty and when I checked the console I got the following error.

core.js:6014 ERROR 
HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:8080/country/bean@gmail.com", ok: false, …}
error:
error: SyntaxError: Unexpected token E in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttpRequest.onLoad (http://localhost:4200/vendor.js:34481:51) at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:3626:31) at Object.onInvokeTask (http://localhost:4200/vendor.js:97626:33) at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:3625:60) at Zone.runTask (http://localhost:4200/polyfills.js:3403:47) at ZoneTask.invokeTask [as invoke] (http://localhost:4200/polyfills.js:3700:34) at invokeTask (http://localhost:4200/polyfills.js:4838:14) at XMLHttpRequest.globalZoneAwareCallback (http://localhost:4200/polyfills.js:4875:21)
text: "England"
__proto__: Object
headers: HttpHeaders
lazyInit: () => {…}
lazyUpdate: null
normalizedNames: Map(0) {}
__proto__: Object
message: "Http failure during parsing for http://localhost:8080/country/bean@gmail.com"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://localhost:8080/country/bean@gmail.com"
__proto__: HttpResponseBase

The backend API is working perfectly and the error is in frontend. I want to get only the country value from the backend as a string. Can someone point me out what's wrong with my approach, please?

UPDATE

As per the answers received I changed the return type of java controller from string to ResponseEntity as follows.

@Autowired                                                                                  
    private SearchRepository user;

    @GetMapping("/country/{email}")
    public ResponseEntity<String> getCountry(@PathVariable("email") String email) {
        return ResponseEntity.ok(user.findCountryByEmail(email));
    }

But the error remains the same. As I understand the error caused because of a syntax error of the JSON response. But I couldn't figure out it. Can anyone point me out this?

2 Answers

You are returning a string and angular trys to parse it as JSON. Wrap your response in a

 ResponseEntity<String> 

in the backend or set the correct responseType in angular’s http call

responseType: 'text'

(You’ll possibly need to use responseType: 'text' as 'json', not sure if that’s still the case in v8) .

return this.http.get<string>(`${API_URL}/country/${email}`, {responseType: ‘text’});

Try on backend change return type:

ResponseEntity<String>

and add on frontend response type Observable:

getCountry(email: string): Observable<string> {
...
}
Related