在Angular单个组件中导入第三方JavaScript库

时间:2018-01-09 17:04:17

标签: angular typescript angular-components angular2-components

我目前正在开发一个Angular4应用程序,我想导入一些 javascript库,但仅用于单个组件。 目前,我可以通过在.angular-cli.json内定义路径来轻松导入此库:

{
   "scripts": [
      "../node_modules/jquery/dist/jquery.min.js",
      "../node_modules/jqueryui/jquery-ui.js",
      "../src/assets/js/jquery/cometd/org-cometd.js",
      "../src/assets/js/jquery/cometd/jquery.cometd.js",
   ],
   ...
}

但是,将为所有应用程序导入上述脚本。有没有办法只为特定组件导入它们? 我试图在组件中导入它们,如下所示,但没有成功。

import { Component, OnInit, ViewEncapsulation, Inject } from '@angular/core';
...
import "../../../../../node_modules/jquery/dist/jquery.min.js";
import "../../../../../node_modules/jqueryui/jquery-ui.js";
import "../../../../assets/js/jquery/cometd/org-cometd.js";
import "../../../../assets/js/jquery/cometd/jquery.cometd.js";

@Component({
   selector: '...',
   templateUrl: '...',
   styleUrls: '...',
   encapsulation: ViewEncapsulation.None
})

export class MyComponent implements OnInit {
   ...
}

[更新] - 我忘了提到我目前正在使用 ViewEncapsulation.None 来将某些css文件中的样式应用到组件中。不确定这个细节是否与问题有关。

3 个答案:

答案 0 :(得分:1)

您可以使用import在组件内导入它们。例如,对于jQuery,它将是

import * as $ from 'jquery';

这意味着“从'jquery'库中”将all全部导入为'$'(并将其用作'$'),并且您实际上不需要在.angular.cli.json中包含另一个导入。它适用于Angular 5(我现在已经测试过了),我认为它也适用于2和4版本。为确保其有效,您可以在console.log($)块中编写ngOnInit(例如)。

答案 1 :(得分:1)

jQuery和bootstrap之类的东西是全局的,可供应用程序使用。但是,优良的做法是使它们可注射,因此可以从单个组件中获取。

首先安装jQuery

npm install --save jquery
npm install -D @types/jquery

第二个制作注射模块

import { NgModule } from '@angular/core';
import { InjectionToken } from '@angular/core';
import * as jquery from 'jquery';

export const JQUERY = new InjectionToken<jquery>('jQuery');

export function _jquery(): jquery {
  return jquery;
}

@NgModule({
  providers: [{
    provide: JQUERY,
    useFactory: _jquery
  }]
})
export class JqueryTokenModule { }

第三,在你的模块中:

providers: [{provide: JQUERY, useValue: _jquery}]

最后,将其注入您的组件

constructor(@Inject(JQUERY) private $) {
  // use `this.$` which is jQuery
}

答案 2 :(得分:0)

您可以通过获取src js并将其导入组件中来实现。

以下是我所做的传单应用程序的示例:

package.json:

"leaflet.markercluster": "^1.1.0",
"leaflet-draw": "^0.4.12",
使用markercluster库示例

random1.component.ts:

declare const L: any;
import 'leaflet.markercluster';

export function initMarkerCluster(map: L.Map, mapService: LeafletService) {
  // Set the ClusterMarkerLayer
  const cluster = L.markerClusterGroup();
  ...
}
使用leaflet.draw库示例

random2.component.ts:

declare const L: any;
import 'leaflet-draw/dist/leaflet.draw-src';

export function drawPlugin(map: L.Map, mapService: LeafletService) {
  const drawnItems: L.FeatureGroup = L.featureGroup().addTo(map);
  const drawControl = initDrawControl(drawnItems);
  map.addControl(drawControl);
  ...
}

注意:在这些传单库中有Leaflet的命名空间L所以我声明了一个全局变量,但你不应该需要它。

相关问题