我的应用程序中有一个服务,我需要在其中使用 Pipe。 在 app.module.ts 文件中,我没有在导入数组中导入 commonModule,因为我使用独立方法。
app.module.ts 导入数组是:
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
IconsModule,
MatDialogModule,
MatSnackBarModule,
HttpClientModule,
],
...
我的服务是这样的:
@Injectable({
providedIn: 'root',
})
export class ExportService {
constructor(private decimalPipe: DecimalPipe) {}
...
}
我可以通过在 app.module.ts 导入数组中添加 CommonModule 来解决问题,如下所示:
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
**CommonModule,** <-- Added in here
AppRoutingModule,
BrowserAnimationsModule,
IconsModule,
MatDialogModule,
MatSnackBarModule,
HttpClientModule,
],
...
但是有没有另一种方法可以实现此目的,并且无需在 appModule 文件中导入 CommonModule?
你不能在构造函数中注入decimalPipe
您可以创建一个新的 DecimalPipe
import { DecimalPipe} from '@angular/common';
import { LOCALE_ID, Inject} from '@angular/core';
constructor(@Inject(LOCALE_ID) private locale:string) {}
doIt()
{
const decimalPipe=new DecimalPipe(this.locale)
return decimalPipe.transform(3.141516,'1.0-3')
}
但是您也可以简单地导入 formatNumber 并使用它
import { formatNumber } from '@angular/common';
import { LOCALE_ID, Inject} from '@angular/core';
constructor(@Inject(LOCALE_ID) private locale:string) {}
doIt()
{
return formatNumber(3.141516,this.locale,'1.0-2')
}