【问题标题】:Cannot Instantiate DatePipe无法实例化 DatePipe
【发布时间】:2017-01-29 04:10:05
【问题描述】:

我正在尝试在我的 Angular2 应用程序中实例化一个 DatePipe 对象,以便在我正在开发的组件中使用 transform(...) 函数。

// ...
import { DatePipe } from '@angular/common';

@Component({...})
export class PanelComponent implements OnInit {
    // ...
    datePipe: DatePipe = new DatePipe(); // Error thrown here
    // ...
}

此代码段在 RC5 中运行良好。现在我正在尝试升级到 Angular2 最终版本并在运行 ng serve 或 ng build 时收到此错误,

~/tmp/broccoli_type_script_compiler-input_base_path-XitPWaey.tmp/0/src/app/panel/panel.component.ts (33, 24): 
Supplied parameters do not match any signature of call target.

我该如何解决这个问题?还有另一种实例化管道的方法吗?还是 Angular 已经停止支持在组件内实例化管道?

【问题讨论】:

  • 您只是以错误的方式使用管道。您不应该手动实例化管道,而是使用 DI。

标签: angular angular2-pipe


【解决方案1】:

如果你看一下源代码,你会看到 DatePipe 构造函数要求一个必需的参数:

constructor(@Inject(LOCALE_ID) private _locale: string) {}

DataPipe 没有默认语言环境

https://github.com/angular/angular/blob/2.0.0/modules/%40angular/common/src/pipes/date_pipe.ts#L97

这就是打字稿给出错误的原因。 这样你必须启动你的变量,如下所示:

datePipeEn: DatePipe = new DatePipe('en-US')
datePipeFr: DatePipe = new DatePipe('fr-FR')
constructor() {
  console.log(this.datePipeEn.transform(new Date(), 'dd MMMM')); // 21 September
  console.log(this.datePipeFr.transform(new Date(), 'dd MMMM')); // 21 septembre
}

希望对你有帮助!

【讨论】:

【解决方案2】:

看起来一切正常,错误必须在代码中的其他任何地方。 见我的小伙伴:https://plnkr.co/edit/koDu6YmB131E6sXc6rKg?p=preview

import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {DatePipe} from '@angular/common';

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
    </div>
  `,
})
export class App {

  dPipe = new DatePipe();

  constructor() {
    this.name = 'Angular2'
    console.dir(this.dPipe);
    console.log(this.dPipe.transform(new Date(), 'dd.MM'));
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

还有@Harry Ninh .. 你不能注入 Pipes!!

【讨论】:

  • 我相信 plunker 仍然使用旧版本的 Angular2。在@yurzui 的回答之后,我确实检查了 DatePipe 类历史记录,发现这个拉取请求在 RC6 中引入了新的构造函数。 fix(i18n): Currency/Date/Number pipe use injected locale
  • 正如this answer 所指出的,您可以注入包括DatePipe 在内的Angular 管道。我用 DatePipe 创建了一个Plunkr example 的依赖注入供参考。
猜你喜欢
  • 2022-01-03
  • 2016-06-09
  • 2020-10-26
  • 2016-11-22
  • 2016-02-29
  • 2020-08-30
  • 2011-02-28
  • 2021-11-26
  • 2012-11-23
相关资源
最近更新 更多