我目前正在开发 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 文件中的样式应用到组件中。不确定此细节是否与问题相关。
最佳答案
像 jQuery 和 bootstrap 这样的东西是全局的,并且可供应用程序使用。但是,最好的做法是使它们可注入(inject),从而可以从单个组件中引用。
首先安装jQuery
npm install --save jquery
npm install -D @types/jquery
第二步制作注入(inject)模块
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}]
最后,将其注入(inject)到您的组件中
constructor(@Inject(JQUERY) private $) {
// use `this.$` which is jQuery
}
关于angular - 在 Angular 单个组件中导入第 3 方 javascript 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48173259/