11

我正在尝试DatePipe在我的 Angular2 应用程序中实例化一个对象,以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 是否停止支持在组件内实例化管道?

4

2 回答 2

28

如果你看一下源代码,你会看到 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
}

希望对你有帮助!

于 2016-09-21T06:15:08.997 回答
0

看起来一切正常,错误必须在代码中的其他任何地方。查看我的插件: 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 .. 你不能注入管道!

于 2016-09-21T05:46:34.157 回答