Q: How to access a variable outside the function in angular I am trying to create a custom pipe to access the data from JSON file and use the data in ts file. I have a issue on how to access the data outside a function.
@Pipe({ name: 'currency' })
export class CurrencyPipe implements PipeTransform {
  constructor(private httpService: HttpClient) { }
  arrCurrencies: any;
  transform(value, country): string {
    if (!value) {
      return ''
    } else {
      if (!country) {
        country = 'NZD'
      }
      const symbol = symbols[country] //value of symbol is $
      if (symbol) {
        this.httpService.get('./assets/locales/en_AU.json').subscribe(
          data => {
            this.arrCurrencies = data;
          });
           console.log('this.arrCurrencies', this.arrCurrencies); // not able to access arrCurrencies outside the func.
            return accounting.formatMoney(value, { symbol, format: '%s %v',precision : this.arrCurrencies.CURRENCYFORMATS.AUD.CURRENCYDECIMALS , thousand: ",",
            decimal : "." })
      }
      return accounting.formatMoney(value, { symbol: country, format: '%v %s' })
    }
  }
}

JSON:
"CURRENCYFORMATS": {
    "DEFAULT": {
        "DECIMALSEPARATOR": ".",
        "THOUSANDSEPARATOR": ",",
        "CURRENCYDECIMALS": "2"
    },
    "AUD": {
        "DECIMALSEPARATOR": ".",
        "THOUSANDSEPARATOR": ",",
        "CURRENCYDECIMALS": "4"
    },
}


A: It seems to me that you're trying to get some info from an async function and use it in a synchronous way. Try this:
import {of} from 'rxjs';
import {map} from 'rxjs/operators';

@Pipe({ name: 'currency' })
export class CurrencyPipe implements PipeTransform {
  constructor(private httpService: HttpClient) { }
  transform(value, country): Observable<string> {
    if (!value) {
      return of(''); // had forgotten this line
    } else {
      if (!country) {
        country = 'NZD'
      }
      const symbol = symbols[country] //value of symbol is $
      if (symbol) {
        return this.httpService.get('./assets/locales/en_AU.json').pipe(
          map(data => accounting.formatMoney(value, { symbol, format: '%s %v',precision : data.CURRENCYFORMATS.AUD.CURRENCYDECIMALS , thousand: ",",
            decimal : "." }));
      }
      return of(accounting.formatMoney(value, { symbol: country, format: '%v %s' }));
    }
  }
}

And you can use it like this (to get R$ 12,00 on screen):
<div>
  {{12 | currency: 'BRL' | async}}
</div>


A: First of all: You should definitely NOT make http calls in pipe. You are making a bazillion of unnecessary api calls.
Imagine you have a product page with 200 prices listed. Your implementation would fire 200 requests only to format the prices on your page for every visit. And on the other hand, you are not unsubscribing the subscriptions. This could quite easily lead to memory leaks.
TLDR:
Just use the default Currency Pipe which comes with angular. It should be sufficient for your use case.
