最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

angular - How to import Javascript library in angular2 globally - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 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 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;
}
发布评论

评论列表(0)

  1. 暂无评论