Angular 2异步http调用导致undefined

时间:2017-08-25 13:37:34

标签: javascript angular http

我试图使用来自api调用的数据,但是当我尝试访问它时,不会返回数据,所以我得到了未定义。下面是代码:

API服务:

public addBusiness(businessObject)
{

    // Testing endpoint dor fake endpoint
    let endPoint = '/business';

    // let endPoint = this.baseUrl+`/business`;

    let content = {businessObject: businessObject};
    let headers = new Headers({ 'Content-Type': 'application/json', 'Accept': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    let body = JSON.stringify(content);

    return this.http.post(endPoint, body, options )
        .map(res => res.json());

}

组件:

this.BusinessApiService.addBusiness(businessObject).subscribe(res => {
      // Check for an success response if there is do:
      if (res.request.status === 'success') {
          console.log('%c addBusiness API call was a success', 'color: green; font-weight: bold;');
          console.log(res);

          let currentQuoteObj = {
              businessId: res.data.businessId,
              applicantIds: []
          };

          this.quoteHandler.saveCurrentQuote(currentQuoteObj);

          let businessId = this.quoteHandler.currentQuote['businessId'];

          let that = this;

          this.applicants.value.forEach(function(applicant) {
              // console.log(applicant);

              console.log(businessId);

              that.BusinessApiService.addApplicant(applicant, businessId).subscribe(res => {
                  if (res.request.status === 'success') {
                      let appicantId = res.data.applicantId;

                      that.quoteHandler.addApplicanToCurrentQuote(appicantId);
                  }
                  else {
                      // Todo add error handling
                      console.log('ITS BROKE');
                  }
              });
          });


          console.log('Current Quote object:');
          console.log(this.quoteHandler.currentQuote);

          console.log('Current Uncompleted Applicant object:');
          console.log(this.quoteHandler.currentUncompletedApplicants);
      }
      // If there is an error handle it here
      else {
          // Todo add error handling
          console.log('%c addBusiness API call was a fail', 'color: red; font-weight: bold;');
          // console.log(res);
      }
  });

添加申请人api与添加业务api调用基本相同。我将如何使其工作,以便它做我想要它做的事情,但它不会在businessId和appicantId上得到未定义。谢谢!

编辑:json我期待从API回来:

{
  "request" : {
    "status" : "success",
    "action" : "Business Created"
  },
  "data":{
    "businessId" : 1021
  }
}

1 个答案:

答案 0 :(得分:1)

它是undefined,因为您不是在等待所有BusinessApiService.addApplicant Observable在访问已解析数据之前发出值。您应该使用RxJsforkJoin运算符来等待所有请求。

forkJoin运算符基本上与rx等效Promise.all,以便查看docs

像:

this.BusinessApiService.addBusiness(businessObject).switchMap(res => {
  if (res.request.status !== 'success') {
    // do error handling here
  }

  let businessId = res.data.businessId;
  this.quoteHandler.saveCurrentQuote({ 
    businessId,
    applicantIds: []
  });

  return Observable.forkJoin(this.applicants.value.map(applicant => {
    return this.BusinessApiService.addApplicant(applicant, businessId);
  }));
}).subscribe(applicantResponses => {
    // do something with your applicant responses
});