在Angular 4中的Promise中将数组连接后显示为未定义的数组

时间:2018-03-09 10:10:19

标签: javascript angular promise

我有一个功能:

filterAllComponent(inputdata) {
    let a=[], b=[],c=[];
    a=  this.getfilterPlaces(inputdata);
    b= this.getfilterTransporter(inputdata);
    c= this.getfilterVehicles(inputdata);

    let getplaceArray = [],
  getTransporterArray = [],
  getVehicleArray = [];

let getPlacePromise = function () {
  const self = this;
  return new Promise(function (resolve, reject) {
    getplaceArray = a;
    resolve("got places\n");
  });
};

let getTransporterPromise = function (message) {
  const self = this;
  return new Promise(function (resolve, reject) {
    getTransporterArray =  b
    resolve(message + "got Transporter");
  });
};

let getVehiclePromise = function (message) {
  const self = this;
  return new Promise(function (resolve, reject) {
    getVehicleArray = c
    resolve(message + "got vehicle");
  });
};

getPlacePromise().then(function (result) {
  return getTransporterPromise(result);
}).then(function (result) {
  return getVehiclePromise(result);
}).then(function (result) {
  var AllDropdownValues = getTransporterArray.concat(getVehicleArray).concat(getplaceArray);
  console.log(AllDropdownValues);
});


}

需要将数组AllDropdownValues与 getVehicleArray getplaceArray getTransporterArray 连接起来。 在最终结果中,数组 getplaceArray 显示未定义。其余结果正确显示。

调用函数:

getfilterTransporter(autocompleteInputData) {

    var k= this.checkRegex(autocompleteInputData);
    this.getfilteredTransporter= this.filterTransporters(k);
    return this.formatTransporterValue(this.getfilteredTransporter);
}
getfilterVehicles(autocompleteInputData) {

  var k= this.checkRegex(autocompleteInputData);
    this.getfilteredVehicle= this.filterVehicles(k);
    return this.formatVehicleValue(this.getfilteredVehicle);
}
getfilterPlaces(autocompleteInputData) {
  if (autocompleteInputData == '' || typeof(autocompleteInputData) == 'object') 
  return null;
  this.placeData.getPlacesFromPig(autocompleteInputData)
  .subscribe(response =>
    return this.formatPigResponse(response);
   }); 

}

对于 getfilterPlaces ,subscribe()用于从API调用中提取数据。但是当我调用函数filterAllComponent()时,没有填充getfilterPLaces,但是其他两个函数都正常。

1 个答案:

答案 0 :(得分:1)

您的代码存在的问题是,订阅中的return expression未作为return value的{​​{1}}返回。这意味着,如果getfilterPlaces function已设置且没有对象,则getfilterPlaces function没有指定return value

问题是,autocompleteInputData似乎是异步函数并返回this.placeData.getPlacesFromPig或类似的东西。避免此问题的一种方法是使用rjxs Observable运算符和async function declaration。为此,您必须将awaitgetfilterPlaces标记为filterAllComponent functions并使用async。此外,a = await this.getfilterPlaces(inputData)需要返回getfilterPlaces。假设Promise返回this.placeData.getPlacesFromPig,代码将如下所示:

rxjs Observable
async function getfilterPlaces(autocompleteInputData) {
  if (autocompleteInputData == '' || typeof(autocompleteInputData) == 'object') 
    return null;
  return this.placeData.getPlacesFromPig(autocompleteInputData)
    .toPromise()
    .then(response => this.formatPigResponse(response));
}