POST 方法在 Angular2 中不起作用

POST method not working in Angular2

我是 Angular2 的新手。我正在尝试从 Angular2 调用简单的 java REST 调用。当我 posting 数据时,我根本没有收到错误,但是我的 java post 方法没有被调用。

角度 2 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);

JavaPOST方法-

@POST
@Path("/insertEmployee")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String insertEmployee(String employee) {
    logger.debug("Employee: " + employee);
    return "Hello";
}

您需要像这样添加订阅-

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

如果你想使用 promise 就这样使用它-

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

这里的问题是预检结果没有通过。 您必须在 Java API 中允许 CORS 请求(您必须添加 Access-Control-Allow-Origin * header,请参阅您的 API lib 文档以了解如何添加它) .

这就是您在订阅时收到错误的原因,因为您的预检请求未通过。

编辑:请参阅 How to make CORS-enabled HTTP requests in Angular 2? 了解有关该问题的更多解释。