0
votes

i try to use pipe but inside my pipe there's async data : my 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;
  }
}
}

And in my component :


 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 the observable and outside the subscription

1

1 Answers

0
votes

I found the solution, apparently we must not use service inside a pipe so i just removed the service from the pipe and call it in the component : in my 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;
 }

In ngOninit :

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

and in the valuePrepareFunction :

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

it worked perfectly i hope it will help someone