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";
}
deen
  • 2,185
  • 7
  • 29
  • 53
  • what is the response you get? add `.subscribe(res => console.log(res))` right after `this.http.post()` to `console.log` the response. – Supamiu Sep 20 '16 at 09: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 'http://localhost:3000' is therefore not allowed access.** – deen Sep 20 '16 at 09:28

2 Answers2

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.

Community
  • 1
  • 1
Supamiu
  • 8,501
  • 7
  • 42
  • 76
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);
Sanket
  • 19,295
  • 10
  • 71
  • 82