0

我想導入angular2中的moment.js庫。 我發現了以下解決方案:如何在angular2全局導入Javascript庫

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

從導入時刻的公共基礎類型導出組件。

家長

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() {} 
} 

更新

另一種方法是使用Dependency Injection寫與Injectable()裝飾服務,這將使你的類加載速度更快。

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

@Injectable() 
export class SomeClass { 
    public moment: any = moment; 
} 
+0

謝謝!這是一個很好的方法。我想等一下,看看有沒有其他的選擇。 – kdu

+0

您不能注入某些未標記爲@injectable的東西。它只是不可能與這樣的第三方庫,除非你把它包裝在一個角度理解服務。這可能是比我上面描述的更好的解決方案,因爲它的可寫性更高。 – KnowHoper

4

從我讀here,我可以舉這樣整個應用程序時提供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) {} 
}