1

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.component.html')
})
export class AppComponent {
  moment:any = moment;
  constructor() {}
}

However, I do not want to import this to every component I have. Is there a way to inject it globally so I can use it in all my components?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
kdu
  • 1,259
  • 4
  • 12
  • 18

2 Answers2

5

Derive your components from a common 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.component.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 composition is preferred over inheritance.

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

@Injectable()
export class SomeClass {
    public moment: any = moment;
}
KnowHoper
  • 4,352
  • 3
  • 39
  • 54
  • Thanks! This is a nice approach. I'd like to wait to see if there are some other alternatives. – kdu Apr 26 '16 at 14:09
  • 1
    You can't inject something something that isn't marked as @injectable. Its just not possible with a 3rd party library like this, unless you wrap it inside a service angular understands. This is probably a better solution than what I described above, because its more compose-able. – KnowHoper Apr 26 '16 at 22:41
5

From 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 component by using DI, like this:

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

@Component({
  selector: 'app',
  template: require('./app.component.html')
})
export class AppComponent {
  constructor(@Inject("moment") private moment) {}
}
kdu
  • 1,259
  • 4
  • 12
  • 18