简体   繁体   English

如何全局导入angular2中的Javascript库

[英]How to import Javascript library in angular2 globally

I'm trying to import the moment.js library in angular2. 我正在尝试在angular2中导入moment.js库。 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. 更好的方法是使用Dependency Injection通过Injectable()装饰器编写服务,这样做更好,因为与继承相比,组合更可取。

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: 从我在这里阅读的内容中,我可以像这样引导整个应用程序时提供momentjs库:

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: 然后,可以使用DI在自己的组件中使用它,如下所示:

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

@Component({
  selector: 'app',
  template: require('./app.component.html')
})
export class AppComponent {
  constructor(@Inject("moment") private moment) {}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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