Search code examples
angulartypescriptfetch-apiangular12

angular 12 custom pipe by fetch data throw service and return string instead of number


Hi Every Mind I have this problem

import { Pipe, PipeTransform } from '@angular/core';
import { PrintingTypesService } from 'src/app/settings/services/printing-types/printing-types.service';
import { PrintingTypesModel } from 'src/app/settings/share/printing-types.model';

@Pipe({
  name: 'printingTypesPipe',
})
export class PrintingTypesPipePipe implements PipeTransform {
  public printingTypesData: PrintingTypesModel[] = [];
  name: any;
  constructor(private printingTypesService: PrintingTypesService) {}

  transform(value: string): any {
    this.printingTypesService.fetchPrintingTypes().subscribe((data) => {
      this.printingTypesData = data;
      const noon = this.printingTypesData.find((o: any) => {
        return Number(o.printing_type_id) === Number(value);
      });
      this.name = '';
      this.name = noon!.name_e;
    });
      return this.name;
  }
}

When I console log this.name it give me string but this string did not appear in browser!!

I Tried but I did not find the main problem? Thanks A lot for your Help :)


Solution

  • change your transform function to return observable like this

      transform(value: string): any {
        return this.printingTypesService.fetchPrintingTypes().pipe(map(data) => {
          this.printingTypesData = data;
          const noon = this.printingTypesData.find((o: any) => {
            return Number(o.printing_type_id) === Number(value);
          });          
          return noon!.name_e;
        });
      }
    

    and in your template use async pipe after printingTypesPipe pipe.for example

    {{ 'test' | printingTypesPipe | async }}