When attempting to utilize the Angular2 http.get function to retrieve data from a Restful Webservice, I encountered an issue where the error status 200 was returned

Angular 2 Issue with http.get Request to Restful Webservice

When I try jsontest.com, I receive the value properly.

 getCurrentTime()
    {
    //return this.http.get('http://date.jsontest.com')
    return this.http.get('http://localhost:8080/webserviceangular2/services/updateUserRecords/')
    .map(res=>res.json());
    }

Another Component.ts Page

import {Component} from 'angular2/core';
import {FormExample} from "./angular-typescript-form.component";
import {Jsonp, URLSearchParams} from 'angular2/http'; 
@Component({
selector: 'my-app',
template: `<angular-typescript-form>loading...</angular-typescript-form>    <br>
<p>{{postData}}</p>
<button (click)="OnTestGet()">Test_get_request</button>
<p>{{getData |json}}</p>
`,
directives: [FormExample],
providers: [FormExample,JSONP_PROVIDERS]
})
export class FormComponent {
constructor(private httpservice: FormExample){}
getData: string;
OnTestPost(){
this.httpservice.postJSON()
}
OnTestGet()
{
this.httpservice.getCurrentTime()
.subscribe(
data=>console.log(this.getData=data),
error=>console.log(JSON.stringify(error)),
()=> console.log("finished"));
}
}

Java Code Snippet

@Path("/updateManager")
public class UpdateManager {
@GET
@Produces("text/plain")
@Consumes("text/plain")
//@Produces("application/json")
//@Consumes("application/json")
@Path("/updateUserRecords/")
public Response updateUserRecords(){        
try {
dbConnection = getDBConnection();
System.out.println("connected is created "+dbConnection);
myStatement = dbConnection.prepareStatement("select * from account");
System.out.println(myStatement);
rs = myStatement.executeQuery();
while (rs.next()) {         
data=rs.getString(3);                                   
}           
ResponseBuilder rb=Response.status(200);
rb.cacheControl(cc);
rb.entity(data);
response=rb.build();            
}catch (Exception e) {
System.out.println(e);
}       
return response;    
}

I am able to retrieve payload value in Java Restful Webservice but encountering errors on the client-side. Can anyone assist me?

Answer №1

It appears that you may need to modify your code in order to send text responses with JSON formatting. Consider updating your @consume and @produces annotations to

@Consumes(MediaType.APPLICATION_JSON),@Produces(MediaType.APPLICATION_JSON)
so that it can properly send responses in JSON format.

Answer №2

Appreciate the help! Interestingly, I made a slight adjustment which ended up resolving the cross origin issue. I inserted the following code at the end of the tomcat7/conf/web.xml file and now everything is functioning smoothly.

<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
  <init-param>
    <param-name>cors.allowed.origins</param-name>
    <param-value>*</param-value>
  </init-param>
  <init-param>
    <param-name>cors.allowed.methods</param-name>
    <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
  </init-param>
  <init-param>
    <param-name>cors.allowed.headers</param-name>
    <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
  </init-param>
  <init-param>
    <param-name>cors.exposed.headers</param-name>
    <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
  </init-param>
  <init-param>
    <param-name>cors.support.credentials</param-name>
    <param-value>true</param-value>
  </init-param>
  <init-param>
    <param-name>cors.preflight.maxage</param-name>
    <param-value>10</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

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

Angular 8: How to Filter an Array of Objects Using Multiple Conditions

I am faced with the following scenario where I need to filter an array of objects based on lineId, subFamily, and status. My current code successfully filters based on lineId, but now I also need to include a condition for subFamilyId. I have two specifi ...

Adjusting the height of Google maps in Angular 4 to occupy the rest of the

I have integrated https://github.com/SebastianM/angular-google-maps into my angular 4 application. In order for the map to display properly, I need to specify the map height in CSS like this: agm-map { height: 300px; } Is there a way for the <agm-m ...

Looking to add some flair to your Android Navigation Architecture? Learn how to seamlessly animate your new fragments sliding

Within the example navigation action set in the navigation graph, there is a transition defined like this: <action android:id="@+id/action_fragment1_to_fragment2" app:destination="@id/fragment2" app:enterAnim="@anim/right_slide_in" app: ...

Does angular-sortablejs work with angular 5?

I attempted to use angular-sortables in combination with the ng-drag-drop library to sort the list items that are being dragged, but it appears that nothing is happening when I try to use it. Does anyone know if angular-sortables is compatible with Angular ...

Having difficulty accessing the value of a table td element in HTML using a jQuery selector

When creating a table, I utilize ng-repeat to generate table rows. Whenever the dropdown changes, a function is triggered which applies certain conditions. Based on these conditions, an object is added to an array that is bound to a scope variable. Here i ...

Error encountered: Angular2 is unable to locate the traceur module after integrating the hltv-api npm

Following a direct npm install of the hltv-api package, I attempted to import it into my component.ts file with the following code: import { getNews, getResults } from 'hltv-api'; I then configured my systemjs.config.js fi ...

Is the child component in Angular re-rendered or re-initialized?

Recently started working with Angular(14) and encountered a problem. Whenever I update a property of the parent component, which is an array, the child component gets re-initialized (running the ngOnInit function). This issue arises when using the child co ...

Can text in a TextView be automatically highlighted?

How can I pre-select a specific area of text on a TextView automatically without the user having to do it themselves when the activity starts? ...

What is the process for implementing a filter to retrieve specific information from the data.gov.in API?

I am currently working on accessing air traffic data for my region using the data.gov.in API. Here is the link to the API I am utilizing. I am interested in learning how to implement a filter to acquire specific city data, such as Noida. ...

Why are @Inject and Injectable important in Angular's Dependency Injection system?

constructor(private smartphoneService: smartphoneService) { } Although I am able to execute the code above without encountering any errors, I find myself pondering on the necessity of using @Inject and Injectable on services, Pipes, and other components. ...

Unable to locate module: The system was unable to find the specified module '@angular-devkit/build-angular/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js'

After encountering an error with Mat Dialog boxes close button not working on IOS devices (refer to Stack Overflow), I decided to downgrade my Angular project from version 14.0.0 to 13.0.0. I followed a solution provided in another Stack Overflow thread. H ...

What is the proper way to utilize environment variables on Heroku for my Angular application?

Currently, I am facing difficulties setting up environment variables (or Config Vars in the Heroku world) such as production=true for my angular app on Heroku. I'm struggling to configure the postinstall and build scripts to make use of them effective ...

Guide to submitting data via POST request and redirecting to a specific URL in Spring MVC

In my Spring MVC application, I have integrated AngularJS on the UI. I have a specific requirement where I gather details from the user (such as product information and amount). The challenge is to securely send this data to a payment gateway through a P ...

`mat chip component in Angular Material is malfunctioning`

Whenever I input a string, it does not display properly within the designated textbox. HTML <mat-form-field class="favorite-fruits"> <mat-label>Favorite Fruits</mat-label> <mat-chip-list #chipList aria- ...

Encountering an issue with Angular's <base href="/projectname/client"> directive causing an error in the index.html file

I am currently working on an Angular 7 application that is deployed on Openshift using a Docker image. I have been trying to configure the application URL to be https://ocp-1123/projectname/client, but whenever I set my base href with "/projectname/client" ...

Leveraging the @Input decorator to send external data into the Angular component

In my Ionic app, I am utilizing an Angular component. Within this component, there is a variable called headerText that is supposed to be initialized from the page where the component is being used. The issue arises when the headerText variable is always ...

Error encountered while performing elliptic curve cryptography due to an invalid key

While attempting elliptical curve cryptography with flexyprovider, I encountered an issue. An InvalidKeyException was thrown, leaving me puzzled as to how to resolve it: Exception in thread "main" java.security.InvalidKeyException: Illegal key size at jav ...

BehaviorSubject does not retain duplicate entries in the array

When adding values to a service and component, the first value in the array changes to the second value. Here is an overview of the code: Service export class PrepayService { private _carts: BehaviorSubject<ShoppingCart[]>; carts : Observable ...

The application is experiencing compilation issues following the creation of mime-type.validator.ts. This problem has been reported by one author

I originally created a file called mime-type.validator.ts. Although I haven't used this file yet in my application, it does exist within my project. However, now my application is failing to compile and displaying the following error message: Faile ...

What is the best way to display suggested words from a given list of options?

Looking for a way to provide suggestions to users based on a list of words they enter in TypeScript while maintaining performance. How can this be achieved efficiently? ...