在 Angular 单个组件中导入 3rd 方 javascript 库 [英] Import 3rd party javascript libraries in Angular single components

查看:21
本文介绍了在 Angular 单个组件中导入 3rd 方 javascript 库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm currently developing an Angular4 application and I want to import some javascript libraries but just for a single component. Currently I can easily import this libraries by defining their paths inside .angular-cli.json like that:

{
   "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",
   ],
   ...
}

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

However, the mentioned scripts will be imported for all the application. Is there a way to import them just for a specific component ? I've tried to import them inside the component like shown below but without success.

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

[UPDATE] - 我忘了提到我目前正在使用 ViewEncapsulation.None 来将一些 css 文件中的样式应用到组件中.不确定此详细信息是否与问题有关.

[UPDATE] - I forgot to mention that I am currently using the ViewEncapsulation.None to be able to apply the styles from some css files into the component. Not sure if this detail can be related with the issue.

推荐答案

诸如 jQuery 和 bootstrap 之类的东西是全局的,可用于应用程序.但是,使它们可注入并因此可从单个组件引用是一种很好的做法.

Things like jQuery and bootstrap are global and will be available to the application. But, it is good practice to make them injectable and thus referable from single components.

首先安装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}]

最后,将其注入到您的组件中

Finally, inject it into your component

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

这篇关于在 Angular 单个组件中导入 3rd 方 javascript 库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆