Mad*_*tm2 6 javascript formatting angular
我创建了一个使用DecimalPipe transform()方法的自定义管道。我在功能模块之一中使用此管道,并且必须将这两个管道都添加到其中providers: [](因为MyCustomPipe使用DecimalPipe),如下所示:
index.ts:
@NgModule({
imports: [
MaterialModule,
SharedModule
],
declarations: [
...
],
providers: [
DecimalPipe,
MyCustomPipe
...
Run Code Online (Sandbox Code Playgroud)
但是,我的目标是不必以这种方式将DecimalPipe添加到功能模块,并且不必在MyCustomPipe和DecimalPipe之间隐藏这种依赖关系,因此,使用MyCustomPipe的人可以担心从SharedModule导入MyCustomPipe。我尝试通过遵循SharedModule模式并从SharedModule导出DecimalPipe来解决此问题(就像我对MyCustomPipe所做的那样),如下所示:
shared.module.ts:
...import { DecimalPipe } from '@angular/common';
...export * from '../pipes/index';
@NgModule({
imports: [
CommonModule,
FormsModule,
HttpModule,
DecimalPipe
],
declarations: [
LoginComponent,
ErrorComponent,
MyCustomPipe,
],
exports: [
CommonModule,
HttpModule,
LoginComponent,
ErrorComponent,
DecimalPipe,
MyCustomPipe
]
})
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试执行此操作时,出现错误"Error: (SystemJS) Unexpected pipe 'DecimalPipe' imported by the module 'SharedModule'. Please add a @NgModule annotation."。现在,我可以declarations: []在SharedModule中添加DecimalPipe ,但是随后出现错误警告我在SharedModule和CommonModule中都声明了DecimalPipe。我认为这是由于我对文档中描述的SharedModule模式缺乏了解。即使这是正确的方法,我也不是100%,因为我从未尝试共享使用内置Angular管道和功能模块的自定义管道。
您无需担心在应用程序中的其他位置使用/重复使用内置DecimalPipe以及使用它的customPipe时,可以将其导入/声明。只需声明customPipe。在您的自定义管道的定义,只是import在DecimalPipe像
import { DecimalPipe } from '@angular/common';
Run Code Online (Sandbox Code Playgroud)
然后在使用它的功能模块中,只需将它们定义为中的declarations数组的一部分@NgModule。如果应该将此功能模块导入其他功能模块中的其他位置以标识该新功能模块中正在使用的该特定管道,则请提及此customPipe,这也是exports早期功能模块(正在重用)的数组声明的一部分。
@NgModule({
imports: [
CommonModule,
...
],
declarations: [
CustomPipe
],
exports: [
CustomPipe // <-- do this only if you need this pipe to be available external to this ReusedFeatureModule when this module is 'imported' to other feature modules
]
})
export class ReusedFeatureModule { }
Run Code Online (Sandbox Code Playgroud)
CustomPipe
import { Pipe, PipeTransform } from '@angular/core';
import { DecimalPipe } from '@angular/common';
@Pipe({
name: 'customPipe'
})
export class CustomPipe implements PipeTransform {
...
private originalDecimalPipe: DecimalPipe; // this variable will have the inbuilt DecimalPipe inside the constructor body
constructor () {
this.originalDecimalPipe = new DecimalPipe('en-US'); // pass the current locale as the argument
}
transform(value: any): any { return <transformed-value>;} // implement your transform
}
Run Code Online (Sandbox Code Playgroud)
您应该将管道添加到declarations不在导入下的位置
@NgModule({
imports: [
CommonModule,
FormsModule,
HttpModule
],
declarations: [
LoginComponent,
ErrorComponent,
MyCustomPipe,
DecimalPipe
],
exports: [
CommonModule,
HttpModule,
LoginComponent,
ErrorComponent,
DecimalPipe,
MyCustomPipe
]
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8220 次 |
| 最近记录: |