The server response value is not appearing in Angular 5

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

Answer №1

The data in the Response Body is not properly formatted as JSON, resulting in the "Invalid character" error during deserialization. The service requires correctly structured JSON.

To fix this issue, update your API to send a valid JSON object by setting the content type to "application/json" and returning an object following the example outlined in the post: Spring MVC - How to return simple String as JSON in Rest Controller

Answer №2

For the console.log to work properly, it should be placed within the .subscribe() function

 To ensure the console.log statement functions correctly, make sure it is inside the .subscribe() method like this:
     this.myService.getData().subscribe(data => {
         this.data = data;
         console.log(this.data);
    });

Answer №3

To ensure the correct response type, make sure to specify responseType as 'text' within the request options object. See below for an example:

return this.http.get(`myApi/ExampleMethod/param`, { responseType: 'text' })
                .pipe(
                    catchError(
                        this.errorHandler.handleError.bind(this)
                    )
                 );

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Access Select without needing to click on the child component

I am curious to learn how to open a Select from blueprint without relying on the click method of the child component used for rendering the select. <UserSelect items={allUsers} popoverProps={{ minimal: false }} noResults={<MenuItem disabled={ ...

Ways to eliminate all attributes and their corresponding values within HTML tags

Hey there, I'm trying to strip away all the attribute values and styles from a tag in html Here's my Input: <div id="content"> <span id="span" data-span="a" aria-describedby="span">span</span> <p class="a b c" style=" ...

What is the best way to guide the user to a different page with PHP once the preventDefault() function in jQuery has been utilized on a

My approach to form validation involves using jQuery, AJAX, and PHP on my website. I utilize PHP for the actual input validation process as I believe it is more secure and prevents users from manipulating scripts through browser source code inspection. Add ...

Enable retrieval of calculated time duration in jQuery time picker

After implementing two separate timepickers for calculating a time duration, I am looking to access this computed duration for further calculations later on the page. How can I retrieve the duration that is already displayed to the user after using the sec ...

Do you typically define a static variable within a function using `this.temp`?

I am looking to implement a static variable within a function that meets the following criteria: It maintains its value across multiple calls to the function It is only accessible within the scope of that function Below is a basic example of how I am mee ...

Obtain the data of the highlighted row in a telerik grid directly from the client side

I am attempting to retrieve the value of a GridBoundColumn with DataField="id" using JavaScript on the client side. When the user clicks on the image button within a row, I need to extract the id for that specific row and then invoke a web method by passin ...

Transforming data with D3.js into a string representation

Recently, I stumbled upon a function called "stringify" that seems like a fantastic tool for converting flat data into a Json format. If this function lives up to its potential, it could potentially save me countless hours of writing recursive code in ASP ...

Issues with TypeScript: Difficulty locating names in HTML templates

I recently upgraded my Angular 7 code to Angular 9 by following the steps outlined in the Angular Upgrade guide. However, upon completion of the migration process, I started encountering numerous "Cannot find name" errors within the HTML templates of my co ...

Attaching the JSON data to ngModel in Angular 2

I have received a json response containing various fields, including the rewards.rewardName value. I'm trying to figure out how to bind this specific value to [(ngModel)] in Angular 2. [ { "id": 18, "gname": "learning ramayanam", "goalCat ...

Automatically refresh your Angular 4 frontend with Spring Boot for seamless integration

Currently, I am in the process of developing a web application using Angular4 and Spring Boot java with gradle. I have successfully configured my gradle tasks following the instructions provided in this resource. By executing ./gradlew bootRun, both Java a ...

Error! React is unable to find the window object

I recently added the "react-speech" package to my application in order to incorporate text-to-speech functionality. However, upon importing the package, I encountered an error that has been challenging to resolve despite extensive research. Any assistance ...

The error TS2339 is indicating that there is no property called myProperty on the type SetStateAction<User>

I'm encountering a TypeScript error while working with React that's leaving me puzzled: <html>TS2339: Property 'subEnd' does not exist on type 'SetStateAction&lt;User&gt;'.<br/>Property 'subEnd' d ...

Having Difficulty with Mathematical Operators in AngularJS

Here is the code snippet I am currently working with: $scope.calculateTotal = function() { $scope.totalAmounts = []; var total = 0; for (var i = 0; i < $scope.orderDetails.length; i++) { console.log($scope.orderDetails[i]['pric ...

The Ajax script triggers the PHP script twice

Utilizing AJAX on my HTML page, I am able to dynamically load data from a MySQL database without reloading the page and send email notifications upon certain events. The process involves Ajax calls to script.php which then makes requests to the database an ...

Unable to pass parameters using ViewBag in jQuery within a partial view

Currently, I am in the process of building an MVC3 application with razor syntax. My focus right now is on developing the partial class that will be responsible for handling comments. This is a snippet of my code: <script src="../../Scripts/jquery.js" ...

Creating nested namespaces with interfaces in Typescript type definitions

In my Javascript project, I am trying to define typing for a specific structure. Consider the following simplified example: a | + A.js + b | + B.js Here we have a folder 'a', and inside it there is another folder 'b'. My goal is t ...

Retrieve the Most Recent Matching Date within an Array

In my mongoDB database, I am searching for datasets with expired date values. When I say expired, I mean that the timestamp of the last element in an array is older than a certain interval from the current timestamp (determined by a category). Each datase ...

CSS navbar with a unique design: Issue with List Hover not Persisting

I'm facing a common issue with a pure CSS navbar. I have constructed a navbar using ul and li elements, but I am unable to make the menus stay visible when I hover over them. The problem lies in the fact that the menu opens only when I hover over the ...

AngularJS allows for dynamic routing within applications

I'm a beginner with AngularJs and I've run into an issue where the URL changes but the page remains the same. Any help would be greatly appreciated. Here is my configuration: var app = angular.module('MyApp', ['ngResource',& ...

The sequence of the exported promise chain in node.js is not executing in a sequential manner when combined

I am currently working with 2 files. The first file, get_data.js, is responsible for retrieving data from an API by acquiring an access token, using that token to access the URL containing the desired data, and then converting the CSV data obtained into JS ...