@Nitzan is correct in that there needs to be a servlet already running by the time you make the POST call.
I have been working on a project that involves an Angular2 front-end and a Java RESTful service for the back end. You can see how it is structured my answer to this question: how to integrate Angular 2 + Java Maven Web Application
For my project, I start the tomcat servlet (version 8.0.27) inside of netbeans, which also serves my app. This ensures that there is a server listening for specific requests made by the app, when the user gets to that point.
Code snippets
data.service.ts
Most of this .ts file came from the Angular Developer guide, credit goes to the author of that.
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class DataService {
constructor (private http: Http) {} // Inject Http client Service
private baseListUrl: string = 'bar/request?id=';
sendInput (input: string) {
let uInput = JSON.stringify({input});
let header = new Headers({'Content-Type': 'MIMETYPE/HERE'});
let options = new RequestOptions({ headers: headers});
this.http.post(this.baseListUrl.concat(input), uInput, options)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
// alert("body: " + body);
return body.docs || {};
}
private handleError (error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
}
foo.java
@Path("bar")
public class Baz{
@POST
@Path("/request")
@Consumes(Mediatype.MIMETYPE_HERE)
public Response doWhatYouNeed(string input) {
// I don't have the exact code for you, but this should serve as a good starting point.
}
}