简体   繁体   English

Angular2:在 Angular2 中使用 Jquery:错误:没有 Token jQuery 的提供者

[英]Angular2 : Using Jquery in Angular2 : Error: No provider for Token jQuery

I want to use Jquery in my Angular2 application.我想在我的 Angular2 应用程序中使用 Jquery。 I did the following:我做了以下事情:

  • I installed using npm package.json我使用 npm package.json安装

    "devDependencies": { "@types/jquery":"2.0.42" }
  • I created a jQuery.service.ts file and declared an OpaqueToken to expose this library我创建了一个jQuery.service.ts文件并声明了一个OpaqueToken来公开这个库

    import { OpaqueToken } from '@angular/core' export let JQ_TOKEN = new OpaqueToken('jQuery');
  • I imported and declared the jQuery token in app.module.ts我在app.module.ts导入并声明了jQuery令牌

    import {JQ_TOKEN} from './common/jQueryService' declare let jQuery : Object;

Now I am trying to access the $ of jQuery in my component.ts file现在我正在尝试访问我的component.ts文件中的 $ jQuery

import {JQ_TOKEN} from './jQueryService'

export class simpleModal {
  @ViewChild('sessionModal') contentEl : ElementRef;

  constructor(private elRef : ElementRef, @Inject(JQ_TOKEN) private $ : any){}

  closeModal() {
    this.$(this.contentEl.nativeElement).modal('hide');
  }
}

And I get the following error:我收到以下错误:

Error: No provider for Token jQuery!错误:没有 Token jQuery 的提供者!

Can someone please guide me on why this error appears?有人可以指导我为什么会出现这个错误吗?

please include jquery file in your index.html and请在您的 index.html 中包含 jquery 文件和

declare jQuery like this declare var jQuery:any;像这样声明 jQuery 声明 var jQuery:any; in your component and you can use it no need to include extra things.在您的组件中,您可以使用它而无需包含额外的东西。

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

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