我正在尝试向后端休息api发送http post请求。这是http服务的代码:
@Injectable()
export class requestService{
constructor(private _http:Http){}
postRequest(request:any){
console.log("Here is post")
const body=JSON.stringify(request);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this._http.post('http://localhost:8080/requests',body,options).map(res=> console.log(res.headers));
}
}
我确信我的后端工作正常。我成功发送邮递员的邮寄请求。但是,当我使用我的服务发送请求时,没有任何反应。没有错误。此外,该对象也不会记录到后端。
那么,问题是什么?
答案 0 :(得分:4)
Observables
很懒。没有订阅,他们就不会做任何事情。
使用subscribe()
代替map()
@Injectable()
export class requestService{
constructor(private _http:Http){}
postRequest(request:any){
console.log("Here is post")
const body=JSON.stringify(request);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this._http.post('http://localhost:8080/requests',body,options).subscribe(res=> console.log(res.headers));
}
}
或在调用者站点返回observable和subscribe:
@Injectable()
export class requestService{
constructor(private _http:Http){}
postRequest(request:any){
console.log("Here is post")
const body=JSON.stringify(request);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this._http.post('http://localhost:8080/requests',body,options).map(res=> console.log(res.headers));
}
}
this.requestService.postRequest.subscribe(val => console.log(val));