@Nitzan是正確的,因爲在進行POST調用時需要一個已經運行的servlet。
我一直在研究一個涉及到後端的Angular2前端和Java RESTful服務的項目。你可以看到它是如何構造的我對這個問題的回答:how to integrate Angular 2 + Java Maven Web Application
對於我的項目,我啓動了netbeans內的tomcat servlet(版本8.0.27),它也服務於我的應用程序。這確保有一個服務器監聽應用程序發出的特定請求,當用戶到達該點時。
代碼片段
data.service.ts
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.
}
}
你需要有一個容器中運行你的servlet,然後做一個HTTP請求(可能POST)該程序的URL。 –
[Angular2 HTTP客戶端](https://angular.io/docs/ts/latest/guide/server-communication.html#!#update) –
我使用eclipse neon與apache tomcat server v9.0 –