【问题标题】:Http post request does not workHttp post请求不起作用
【发布时间】:2016-10-02 09:44:03
【问题描述】:

我正在尝试向后端 rest 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));

    }

}

我确信我的后端工作正常。我成功地通过邮递员发送了一个帖子请求。但是,当我使用我的服务发送请求时,什么也没有发生。没有错误。另外,对象也不会记录到后端。

那么,问题出在哪里?

【问题讨论】:

  • 试试这个----this._http.post('http://localhost:8080/requests',body,options).map(res=> console.log(res.data));
  • 我不知道角度,但你确定你甚至发现了错误吗?你在某处有错误回调吗?
  • @micronyks 它不起作用。
  • 你在控制台中得到标题吗?

标签: angular


【解决方案1】:

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 并在调用方站点订阅:

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

【讨论】:

    猜你喜欢
    • 2015-09-30
    • 2015-07-07
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-04
    • 1970-01-01
    相关资源
    最近更新 更多