0

I am new in Angular2. I am trying to call simple java REST call from Angular2. When I am posting data I am not getting error at all but my java post method is not called.

Angular2 POST-

let emplyee = JSON.stringify(this.object);
    let url = 'http://localhost:8080/rest-app/rest/employeeService/insertEmployee';
    console.log("Data: " + emplyee);
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({headers: headers});
    this.http.post(url, emplyee, options);

Java POST method-

@POST
@Path("/insertEmployee")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String insertEmployee(String employee) {
    logger.debug("Employee: " + employee);
    return "Hello";
}
2
  • what is the response you get? add .subscribe(res => console.log(res)) right after this.http.post() to console.log the response. Commented Sep 20, 2016 at 9:25
  • @Supamiu thnx for response, this response I got, Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost:3000' is therefore not allowed access. Commented Sep 20, 2016 at 9:28

2 Answers 2

1

The problem here is that the preflight resuest doesn't pass. You have to allow CORS requests in your Java API (you have to add Access-Control-Allow-Origin * header, see your API lib doc to know how to add it).

That's why you get an error in subscribe, because your preflight request doesn't pass.

EDIT: see How to make CORS-enabled HTTP requests in Angular 2? for more explanations on the problem.

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

Comments

0

You need to add subscribe like this-

    this.http.post(url, emplyee, options)
    .subscribe((response) => {
            //handle response here
    })
    .catch(this.handleError);

If you want to use promise then use it like this-

    this.http.post(url, employee, options)
        .toPromise()
        .then(this.extractData)
        .catch(this.handleError);

Comments

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.