如何以独立方式将通用模块 api 使用到服务中

问题描述 投票:0回答:1

我的应用程序中有一个服务,我需要在其中使用 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?

angular angular-pipe angular-standalone-components
1个回答
0
投票

你不能在构造函数中注入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')
}
© www.soinside.com 2019 - 2024. All rights reserved.