首页 > 解决方案 > 在具有异步数据的 ng2 智能表中使用管道

问题描述

我尝试使用管道,但在我的管道中有异步数据:我的管道:

import { Pipe, PipeTransform } from "@angular/core";
import { VehiculeService } from "app/pages/fleetManagement/services/vehicule.service";
import { map } from "rxjs/operators";
@Pipe({
  name: "convertVehicule"
})
export class ConvertVehiculePipe implements PipeTransform {
  public result: any;
  constructor(private vehicleService: VehiculeService) {}

  transform(value) {
    this.vehicleService
      .getVehicules()
      .pipe(
        map((data: any = []) => {
          let result;
          for (let j = 0; j < data.length; j++) {
            if (value === data[j].id) {
              result = data[j].registration_number;
            }
          }
          return result;
        })
      )
      .subscribe(
        (data: any = []) => {
          console.log(data);
          this.result = data;
        }, //   },
        error => {
          console.log(error);
        }
      );
    console.log(this.result);
    return this.result;
  }
}
}

在我的组件中:


 this.settings = { ...,
  vehicule_fleet_id: {
          title:"vehicle id",
          type: "html",
          editor: {
            type: "custom",
            component: SelectAssuranceComponent
          },
          valuePrepareFunction: cell => {
            let formated = this.convertVehiclePipe.transform(cell);
            return formated;
          }
        }
      }

我这样做了,但是 console.log(this.result) 是未定义的,我不知道问题是不是时间问题,因为 valuePrepareFunction 是直接渲染的,还是问题出在管道函数中,正是订阅内的变量范围可观察的和订阅之外的

标签: angularpipeobservableng2-smart-table

解决方案


我找到了解决方案,显然我们不能在管道内使用服务,所以我只是从管道中删除了服务并在组件中调用它:在我的管道中:

transform(value, data) {
let result;
console.log(value);
console.log(data);
for (let j = 0; j < data.length; j++) {
  if (value === data[j].id) {
    result = data[j].registration_number;
    console.log(result);
  }
}
console.log(result);
return result;
 }

在 ngOninit 中:

   ngOnInit(): void {
    this.vehiculeService.getVehicules().subscribe(data => {
      this.vehicleData = data;
    })
     };

在 valuePrepareFunction 中:

 valuePrepareFunction: cell => {
                console.log(cell);
                let formated = this.convertVehiclePipe.transform(
                  cell,
                  this.vehicleData
                );
                console.log(formated);
                return formated;
              }

它工作得很好,我希望它能帮助别人


推荐阅读