1

angular2にmoment.jsライブラリをインポートしようとしています。次の解決策を見つけました:

import {Component} from 'angular2/core';
import * as moment from 'moment';

@Component({
  selector: 'app',
  template: require('./app.component.html')
})
export class AppComponent {
  moment:any = moment;
  constructor() {}
}

ただし、これをすべてのコンポーネントにインポートしたくはありません。すべてのコンポーネントで使用できるようにグローバルに注入する方法はありますか?

4

2 に答える 2

5

モーメントをインポートする共通の基本タイプからコンポーネントを派生させます。

import * as moment from 'moment';

export class MomentAwareClass {
  moment:any = moment;
  constructor() {}
}

import {Component} from 'angular2/core';

@Component({
  selector: 'app',
  template: require('./app.component.html')
})
export class AppComponent extends MomentAwareClass  {
  constructor() {}
}

アップデート

より良い方法は、依存性注入を使用してデコレーターでサービスを作成することInjectable()です。これは、継承よりも構成が優先されるため、より優れています。

import { Injectable } from '@angular/core';
import * as moment from 'moment';

@Injectable()
export class SomeClass {
    public moment: any = moment;
}
于 2016-04-26T03:25:54.293 に答える
5

ここで読んだことから、次のようにアプリケーション全体をブートストラップするときに momentjs ライブラリを提供できます。

import * as moment from 'moment';
import {provide} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';

bootstrap(App, [
    provide("moment", {useValue:moment})
])

次に、次のように、DI を使用して独自のコンポーネントで使用できます。

import {Component, OnInit, Inject} from 'angular2/core';

@Component({
  selector: 'app',
  template: require('./app.component.html')
})
export class AppComponent {
  constructor(@Inject("moment") private moment) {}
}
于 2016-04-26T21:59:49.307 に答える