首页 > 解决方案 > 错误:模板解析错误:找不到管道“currencySeparator”

问题描述

当我尝试在模板中使用自定义管道时出现错误:

Error: Template parse errors:
The pipe 'currencySeperator' could not be found

这是CurrencySeperatorPipe

import { Pipe, PipeTransform } from '@angular/core';

    @Pipe({
        name: 'currencySeperator'
    })
    export class  CurrencySeperatorPipe implements PipeTransform {
        transform(value: any, decimalSp: string = ',', thousandSp: string = '.'): number {
            return this.localeString(value,decimalSp,thousandSp);
        }

        missingOneDecimalCheck(nStr) {
            nStr += '';
            const x = nStr.split(',')[1];
            if (x && x.length === 1) return true;
            return false;
        }

        missingAllDecimalsCheck(nStr) {
            nStr += '';
            const x = nStr.split(',')[1];
            if (!x) return true;
            return false;
        }

        localeString(nStr,decimalSp,thousandSp) {
            if (nStr === '') return '';
            let x, x1, x2, rgx, y1, y2;
            nStr += '';
            x = nStr.split(thousandSp);
            x1 = x[0];
            x2 = x.length > 1 ? decimalSp + x[1] : '';
            rgx = /(\d+)(\d{3})/;
            while (rgx.test(x1)) {
                x1 = x1.replace(rgx, '$1' + thousandSp + '$2');
            }

            /** If value was inputed by user, it could have many decimals(up to 7)
                so we need to reformat previous x1 results */
            if (x1.indexOf(decimalSp) !== -1) {
                y1 = x1.slice(x1.lastIndexOf(decimalSp)).replace(/\./g, '');

                y2 = x1.split(decimalSp);
                x = y2[0] + y1;
            } else {
                x = x1 + x2;
                if (this.missingOneDecimalCheck(x)) return x += '0';
                if (this.missingAllDecimalsCheck(x)) return x += `${decimalSp}00`;
            }

            return x;
        }
    }

所以我创建了pipe.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CurrencySeperatorPipe } from './currency-seperator.pipe';

    @NgModule({
      declarations: [CurrencySeperatorPipe],
      imports: [],
      exports:[CurrencySeperatorPipe]
    })
    export class PipeModule {
      static forRoot() {
        return {
          ngModule: PipeModule,
          providers: [],
        };
      }
    }

我将此模块导入app.module.ts

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
...
    PipeModule.forRoot(),
  ],
  providers: [],
  bootstrap: [AppComponent],
  entryComponents: [
    ModalComponent,
    LoginComponent
  ],
})
export class AppModule { }

当我尝试使用{{price | currencySeperator:',':'.'}}像这样在模板中它给了我这个错误。

我怎样才能解决这个问题?

谢谢

标签: javascriptangular

解决方案


不需要在 AppModule 中导入 PipeModule,而是在使用管道的组件所在的模块中导入。


推荐阅读