如何从方法外取值?

How to take value outside from the method?

我用了下面的货币格式管道方法

@Pipe({
  name: 'currencyFormat'
 })
export class CurrencyFormat {
  constructor() { }
  transform(value: number,
            currencySign :'$',
            decimalLength: number = 2,
            chunkDelimiter: string = ',',
            decimalDelimiter: string = '.',
            chunkLength: number = 3
           ): 
  string {
         let result = '\d(?=(\d{' + chunkLength + '})+' + (decimalLength > 0 ? '\D' : '$') + ')';
         let num = value.toFixed(Math.max(0, ~~decimalLength));
         return (decimalDelimiter ? num.replace('.', decimalDelimiter) : num).replace(new RegExp(result, 'g'), '$&' + chunkDelimiter) + currencySign;
       }
 }

但是我必须从另一个名为 "contextService" 的服务中分配货币符号。这意味着下面

this.contextService.company.subscribe(param => {
    this.currencySymbol = param.currencyCode.toString();
  })

现在货币代码保存在变量“currencySymbol”中。

我没有直接给出货币符号,而是必须在 currencySign

中分配上述方法

我试过分配喜欢

  transform(value: number,
     currencySign = this.contextService.company.subscribe(param => {
             this.currencySymbol = param.currencyCode.toString();
            }),
     decimalLength: number = 2,
     chunkDelimiter: string = ',',
     decimalDelimiter: string = '.',
     chunkLength: number = 3
   }

以上方法无效。当我安慰时,我得到它作为 [object,object]

我怎么解决这个问题??是否有任何其他方法将值保存在 currencySign??

您从服务器收到的数据在对象上 type.please 在处理之前将其转换为字符串。

  transform(value: number,
     currencySign = this.contextService.company.subscribe(param => {
             let convertedParam  = JSON.stringify(param);
             this.currencySymbol = convertedParam.currencyCode;
            }),

您可以在 CurrencyFormat 管道内添加一个新的 属性 currencySign。将 ContextService 注入 CurrencyFormat 管道并从构造函数订阅公司 属性。这将使 currencySign 属性 始终保持更新。然后你可以直接使用它而不需要将它作为参数传递给transform方法。

@Pipe({
  name: 'currencyFormat'
})
export class CurrencyFormat {

  currencySign = '$';

  constructor(private contextService: ContextService) {
    this.contextService.company.subscribe(param => {
      this.currencySign = param.currencyCode.toString();
    })
  }

  transform(value: number,
    decimalLength: number = 2,
    chunkDelimiter: string = ',',
    decimalDelimiter: string = '.',
    chunkLength: number = 3
  ): string {
    let result = '\d(?=(\d{' + chunkLength + '})+' + (decimalLength > 0 ? '\D' : '$') + ')';
    let num = value.toFixed(Math.max(0, ~~decimalLength));
    return (decimalDelimiter ? num.replace('.', decimalDelimiter) : num).replace(new RegExp(result, 'g'), '$&' + chunkDelimiter) + this.currencySign;
  }
}

现在我们有 $ 作为默认货币。只要有变化,它就会用 ContextService 中的货币进行更新。