0

I need to find province name from angular so I write a pipe service for find name with code this is my code pipe

export class ConvertStatePipe implements PipeTransform {
  constructor(private callData: CallDataService) {}

  transform(value: string): any {
    let nameProvince = '';
    this.callData.getAllProvinces().subscribe( (res) => {
      for (const item of res.provinces) {
        if (item.provinceCode === value) {
          nameProvince = item.name;
        }
      }
    });
    return nameProvince;
  }

here I called CallDataService, from CallDataService I have a function Which is called getAllProvinces, I take all Provinces from API now I set for because I need to find Province name and return name from HTML this my HTML code

<div class="mb-24 terminal-item" fxFlex="33.33333%">
   <strong>Province</strong>
   {{userData.state | convertState }}
</div>

but I can`t retunr variable nameProvince because this undefined and i think because this.callData.getAllProvinces() not async, are you have any idea ?

nima amr
  • 603
  • 1
  • 6
  • 13
  • Please read the canonical https://stackoverflow.com/q/14220321/3001761 - in this case, you could return an *observable* of the value and use `| async` to resolve it. – jonrsharpe Jul 01 '20 at 16:21

1 Answers1

-1
  1. return a observable from your pipe
  2. use async pipe with you pipe that will resolve the subscription for you

-- Try update it like below:

   {{userData.state | async | convertState }}

// in your pipe

        export class ConvertStatePipe implements PipeTransform {
          constructor(private callData: CallDataService) {}
        
          transform(value: string): any {
            let nameProvince = '';
    // update below to return observable
    
          nameProvince =  this.callData.getAllProvinces().pipe( map((res) => {
              let value = '';
for (const item of res.provinces) {
                if (item.provinceCode === value) {
                  value  =  item.name;
                }
              }
return value;
            }));
            return nameProvince;
          }
  • do not subscribe in the pipe transform , just use rxjs pipe and map operator to do filtering and it will return a observable rest async pipe will take care to resolve it.
LogicBlower
  • 1,250
  • 1
  • 8
  • 14