簡體   English   中英

在具有異步數據的 ng2 智能表中使用 pipe

[英]Using pipe in ng2 smart table with async data

我嘗試使用 pipe 但在我的 pipe 里面有異步數據:我的 pipe:

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;
          }
        }
      }

I did this but the console.log(this.result) is undefined, i don't know if the problem is the timing because the valuePrepareFunction is rendred directly or the problem is in the pipe function, precisely the variable scope inside the subscription to可觀察的和訂閱之外的

我找到了解決方案,顯然我們不能在 pipe 中使用服務,所以我只是從 pipe 中刪除了服務並在組件中調用它:在我的 pipe 中:

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;
              }

它工作得很好,我希望它能幫助別人

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM