I'm trying to import the moment.js library in angular2. I found the following solution as:
import {Component} from 'angular2/core';
import * as moment from 'moment';
@Component({
selector: 'app',
template: require('./appponent.html')
})
export class AppComponent {
moment:any = moment;
constructor() {}
}
However, I do not want to import this to every ponent I have. Is there a way to inject it globally so I can use it in all my ponents?
I'm trying to import the moment.js library in angular2. I found the following solution as:
import {Component} from 'angular2/core';
import * as moment from 'moment';
@Component({
selector: 'app',
template: require('./app.ponent.html')
})
export class AppComponent {
moment:any = moment;
constructor() {}
}
However, I do not want to import this to every ponent I have. Is there a way to inject it globally so I can use it in all my ponents?
Share Improve this question edited Apr 1, 2017 at 20:21 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Apr 25, 2016 at 22:51 kdukdu 1,2594 gold badges12 silver badges18 bronze badges2 Answers
Reset to default 5From what I read here, I can provide the momentjs library when bootstrap the whole application like this:
import * as moment from 'moment';
import {provide} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
bootstrap(App, [
provide("moment", {useValue:moment})
])
Then I can use it in my own ponent by using DI, like this:
import {Component, OnInit, Inject} from 'angular2/core';
@Component({
selector: 'app',
template: require('./app.ponent.html')
})
export class AppComponent {
constructor(@Inject("moment") private moment) {}
}
Derive your ponents from a mon base type that imports moment.
Parent
import * as moment from 'moment';
export class MomentAwareClass {
moment:any = moment;
constructor() {}
}
Child
import {Component} from 'angular2/core';
@Component({
selector: 'app',
template: require('./app.ponent.html')
})
export class AppComponent extends MomentAwareClass {
constructor() {}
}
Update
A better way is to use Dependency Injection to write a service with the Injectable()
decorator, this is better as position is preferred over inheritance.
import { Injectable } from '@angular/core';
import * as moment from 'moment';
@Injectable()
export class SomeClass {
public moment: any = moment;
}