deen
deen

Reputation: 2305

POST method not working in Angular2

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

Upvotes: 0

Views: 928

Answers (2)

Supamiu
Supamiu

Reputation: 8731

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.

Upvotes: 1

Sanket
Sanket

Reputation: 19997

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

Upvotes: 0

Related Questions