【问题标题】:get promise data through intermediate service angular 5通过中间服务 Angular 5 获取承诺数据
【发布时间】:2018-06-19 17:52:39
【问题描述】:

我在通过中间服务获取承诺数据时遇到问题。

有组件、中间服务和http服务。

我的组件调用中间服务,然后通过中间服务调用到http服务。

Http 服务返回承诺数据,我认为我无法在中间服务中处理它,因此没有任何内容返回到我的组件。

当我直接从组件调用 Http 服务时,它运行良好,我在 UI 上看到了数据。

任何帮助将不胜感激。

组件代码。 这是从中间服务调用方法的方法

public getDriversAndCars(){
    let promise = new Promise((resolve, reject) => {

        this.vehicleService.getVehicle()       
        .then(
          res => {                                    
           console.log("length"+this.listOfVehicles.length)
           this.getDriver();
         resolve();

        },
          msg => { // Error
          reject(msg);
          }
        );
    });
    return promise;
  }

来自中间服务的代码

public getVehicle(): Promise<Vehicle[]> {

    this.associationservice.getVehicle(25, this.currentPageIndex, this.searchText)
      .then(
        res => {
          this.apimodel = res                         
          console.log("data" + this.listOfVehicles[0].assignedTo)
        },

    )
    return Promise.resolve(this.convertToVehicleModels(this.apimodel));

  }

来自 Http 服务的代码

getVehicle(pageNumber: number,pageIndex: number, searchKeyword: string): Promise<VehicleResourceApiModel> {

    if (pageIndex !== 0 && searchKeyword.trim() !== '' && pageNumber !== 0) {
        // tslint:disable-next-line:max-line-length
        return  this.http.get<VehicleResourceApiModel>(api).toPromise()
        .then(response => {
            return response
        })
        .catch(err => err);

【问题讨论】:

    标签: angular


    【解决方案1】:

    看起来您的中间服务可能是问题所在。您正在为 this.convertToVehicleModels(this.apimodel) 返回已解决的承诺,而 this.apimodel 仍未定义。您的客户端会立即返回此函数的结果,而您的关联服务仍在检索并返回您的实际数据。

    我建议你像这样修改你的中间服务......

    public getVehicle(): Promise<Vehicle[]> {
        return this.associationservice.getVehicle(25, this.currentPageIndex, this.searchText)
          .then(res => this.convertToVehicleModels(res))
    }
    

    这样,convertToVehicleModels 方法在从服务中检索到您的实际数据之前不会被调用,而您从 getVehicle 的返回值是该承诺链的结果。

    【讨论】:

      猜你喜欢
      • 2016-05-14
      • 2015-08-12
      • 1970-01-01
      • 2013-12-19
      • 2017-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-17
      相关资源
      最近更新 更多