如何在DotNet生成的Angular项目中添加JQuery?

时间:2017-04-14 06:36:31

标签: javascript angular

我已经初始化了视图后为我的主题做了一些初始化。 我已经实施了AfterViewInit,我设法导入了jquery:

import * as $ from 'jquery';

但现在我需要执行此操作:

ngAfterViewInit() {
    $(document).trigger('nifty.ready');
}

我有麻烦,因为在这一点上,文件似乎不为人所知。我想我应该有另一个import,但我无法从哪里找到? 我的整个app.component.ts

import { Component, AfterViewInit } from '@angular/core';
import * as $ from 'jquery';

@Component({
    selector: 'app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
    ngAfterViewInit() {
        $(document).trigger('nifty.ready');
    }
}

我得到的错误:

  

异常:调用节点模块失败,错误:TypeError:不能   阅读财产'文件'在module.exports.module.exports中未定义   (E:\ My \ Clients \ AppClientApp \ dist \ vendor.js:12879:12)at   AppComponent.ngAfterViewInit

修改

您可以找到here整个网络应用部分。

EDIT2 事实上,我认为jquery根本没有正确初始化,一旦加载(没有错误),window.jquery返回undefined ......任何想法为什么?

3 个答案:

答案 0 :(得分:1)

您可以将文档注入组件中。

https://angular.io/docs/ts/latest/api/platform-browser/index/DOCUMENT-let.html

import { Component, AfterViewInit, Inject } from '@angular/core';
import {DOCUMENT} from "@angular/platform-browser";

@Component({
  selector: 'app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
  constructor(@Inject(DOCUMENT) private document) {
  }
}

答案 1 :(得分:0)

而不是导入jquery尝试这个 -

declare var jQuery:any;

jQuery(document);

console.log jQuery(document)确定

P.S确保窗口范围内有jquery!

答案 2 :(得分:0)

我看了你的项目。好吧,我没有测试所有.Net功能,但我猜你的webpack配置错过了jQuery的插件提供程序(过去由angular-cli完成)。

所以你做过:

npm install jquery --save

试试这个:

npm install @types/jquery --save-dev

然后将jquery插件提供程序添加到webpack.config.js

  plugins: [
      new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery'
      })
    ]

最后导入如下:

import "jquery";
declare var $: any;