如何在 Angular 5 中正确使用 rest api post?
how to use rest api post correctly with Angular 5?
我在 angular 5 申请中有以下服务:
const httpOptions = {
headers: new HttpHeaders({
'Accept': 'application/json',
'Content-Type': 'application/json'
})
};
addTrip(trip: Trip): Observable<any> {
console.log('Adding trip ' + JSON.stringify(trip));
return this.http.post(`${this.baseUrl}/Trips/trip/`, JSON.stringify(trip), httpOptions);
}
旅行样子(在angular):
export interface Trip {
description: string;
}
java代码是使用rest的seam组件api:
@Name("tripFacadeREST")
@Scope(ScopeType.EVENT)
@Path("Trips")
public class TripFacadeREST {
@In private TripDaoHibernateImpl tripDao;
...
@POST
@Path("Trip")
@Consumes("application/json")
public Response addNewTrip(Trip newTrip) {
tripDao.addTrip(newTrip);
return Response.ok().entity("trip added successfully").build();
}
我无法让这个调用正常工作,我也尝试过 put 但我知道 put 是为了更新,因为 id 是在我使用的服务器端创建的 post,
服务器端未被触发。知道如何解决这个问题吗?
(我能够在同一个服务中使用 GET 注释,没有任何问题)。
您的 HttpClient 代码看起来没问题 - 由于您在网络选项卡中没有看到任何内容,我敢打赌您没有订阅 addTrip
返回的 Observable。
如果您不订阅可观察对象,它将不会被执行。
来自文档:
Always subscribe!
An HttpClient method does not begin its HTTP request until you call subscribe() on the observable returned by that method. This is true for all HttpClient methods.
我在 angular 5 申请中有以下服务:
const httpOptions = {
headers: new HttpHeaders({
'Accept': 'application/json',
'Content-Type': 'application/json'
})
};
addTrip(trip: Trip): Observable<any> {
console.log('Adding trip ' + JSON.stringify(trip));
return this.http.post(`${this.baseUrl}/Trips/trip/`, JSON.stringify(trip), httpOptions);
}
旅行样子(在angular):
export interface Trip {
description: string;
}
java代码是使用rest的seam组件api:
@Name("tripFacadeREST")
@Scope(ScopeType.EVENT)
@Path("Trips")
public class TripFacadeREST {
@In private TripDaoHibernateImpl tripDao;
...
@POST
@Path("Trip")
@Consumes("application/json")
public Response addNewTrip(Trip newTrip) {
tripDao.addTrip(newTrip);
return Response.ok().entity("trip added successfully").build();
}
我无法让这个调用正常工作,我也尝试过 put 但我知道 put 是为了更新,因为 id 是在我使用的服务器端创建的 post, 服务器端未被触发。知道如何解决这个问题吗? (我能够在同一个服务中使用 GET 注释,没有任何问题)。
您的 HttpClient 代码看起来没问题 - 由于您在网络选项卡中没有看到任何内容,我敢打赌您没有订阅 addTrip
返回的 Observable。
如果您不订阅可观察对象,它将不会被执行。
来自文档:
Always subscribe!
An HttpClient method does not begin its HTTP request until you call subscribe() on the observable returned by that method. This is true for all HttpClient methods.