如何从Angular2中的http post方法获取返回值?

时间:2017-07-06 21:08:12

标签: angular

我有一个要求,我需要向Web API发出http post方法请求,即保存用户输入的一些数据。 Web API将返回一些值作为结果,此结果将用于某些UI逻辑。

我尝试以同步方式发布http帖子,但它无法按预期正常工作。

Angular2组件调用此服务来保存数据: -

public SaveCubeReport(userName: any, cubeReport: CubeReportViewModel, APIServiceURL: any)
    {
        var result = this.SaveData(userName, cubeReport, APIServiceURL).subscribe(
            data => {
                console.log(data);
            });

        console.log(result);
}

Http post方法调用如下: -

SaveData(userName: any, cubeReport: CubeReportViewModel, APIServiceURL: any)
{
    var temp = this._http.post(APIServiceURL, JSON.stringify(cubeReport), { headers: ContentHeaders })
        .map((res: Response) => res.json())
        .do(() => {
            console.log('request finished');
        });
    return res;
}

调用angular2-modal弹出窗口的父组件。

var dialog = this.modal.open(SaveCubeReport, overlayConfigFactory(
{
    ReportName: this.ReportItem.rpt_name,
    ReportDescription: this.ReportItem.rpt_description,
    Application: this.ReportItem.application_name,
    Owner: this.ReportItem.owner,
    CubeId: this.CubeId,
    ReportId: this.ReportItem.rpt_id,
    ReportJson: JSON.stringify(this.getState())
}, BSModalContext));

dialog
.then((d) => d.result)
.then((r) => {
    // success
    console.log("Dialog ended with success: ", r);
    this.RefreshReportListDropdown(r);
}, (error) => {
    // failure 
    console.log("Dialog ended with failure: ", error);
});

进行服务调用的功能

RefreshReportListDropdown(savedReportName: any)
{
    this._ClientAPIService.GetCubeReportsListByCubeWithEmptyRecord(this._SessionService.LoggedInUser, this._SessionService.SelectedApplication, this.cubeName, this._SessionService.ClientAPIServiceURL)
        .subscribe(
        (res) => {
            this.cubeReportList = res; //This result should contain all records including the recently saved data from the popup
            ....
        }
    );
}

我的所有请求都是异步请求,即它不等待获取返回值。 这里有什么错误?

2 个答案:

答案 0 :(得分:2)

SaveData方法中返回http.post调用的结果。

SaveData(userName: any, cubeReport: CubeReportViewModel, APIServiceURL: any)
{
    return this._http.post(APIServiceURL, JSON.stringify(cubeReport), { headers: ContentHeaders })
        .map((res: Response) => res.json())
        .do(() => {
            console.log('request finished');
        });
}

在此之后,您的消费者组件中的subscribe将正常工作。

答案 1 :(得分:1)

loginservice.ts:

  checklogin(user) {   
   return this.http.post("API_URL",user).map(resp => resp.json());
  }

logincomponent.ts:

   localvariable={} // or whatever u want 

   customFunction () {
     this.loginservice.checklogin(this.user).subscribe (data => 
     {this.localvariable=data;}) 

     // results is assigned now to this.localvariable
     //write your logic etc ... 
     }