2016-10-02 227 views
1

我想发送一个http post请求到后端rest api。这里是http服务的代码:Http post请求不起作用

@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

试试这个----'this._http.post ('http:// localhost:8080/requests',body,options).map(res => console.log(res.data));' – micronyks

+0

我不知道角度,但你确定y你甚至会发现错误?你是否有错误的回调? –

+0

@micronyks它不起作用。 –

回答

3

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)); 

    } 
} 

或返回观察到的,在主叫方网站订阅:

@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));