简体   繁体   中英

How to import Javascript library in angular2 globally

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?

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;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM