在 component.ts 中找不到名称“$”

Cannot find name '$' in component.ts

我在 angular 网络应用程序的编译时遇到错误:'Cannot find name '$'in component'。当我使用 const $ : any = ''; 然后解决了错误但在浏览器控制台中出现另一个错误:'core.js:1440 ERROR TypeError: $ is not a function' 并且在使用 const $ : any = ''; 时数据表也不起作用。

下面是我的用户组件代码。此组件用于将用户列表放入数据表中。

users.component.ts

import {DataService} from './../services/data.service';
import {Component, OnInit} from '@angular/core';
import {API_ENDPOINT} from '../app.module';
import {Response} from '@angular/http/src/static_response';


const $: any = '';

@Component({
    selector: 'app-users',
    templateUrl: './users.component.html',
    styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {

    private url = API_ENDPOINT + '/admin_api/users';
    private users: any;

    constructor(private dataService: DataService) {
    }

    ngOnInit() {
        this.dataService.get(this.url)
            .subscribe(responce => {
                this.users = responce.data.users;
                if (this.users) {
                    setTimeout(function () {
                        var oTable1 = $('#sample-table-2').dataTable({
                            "aoColumns": [
                                {"bSortable": false},
                                null, null, null, null, null,
                                {"bSortable": false}
                            ],
                        });
                    }, 3000);
                }
            })
    }
}

我见过类似的,对我有用的解决方案是,

  1. 安装jQuery

    npm install jquery --save

  2. 安装类型jQuery

    npm install @types/jquery

  3. 将其导入您的模块

    //THis is important import * as $ from 'jquery';

希望这对您有所帮助!

  • 在控制台中首先安装jQuery
npm install --save jquery
  • 并安装jQuery定义
npm install -D @types/jquery
  • 在你的组件
  • 中调用你的 jquery
import {DataService} from './../services/data.service';
import {Component, OnInit} from '@angular/core';
import {API_ENDPOINT} from '../app.module';
import {Response} from '@angular/http/src/static_response';
import * as $ from 'jquery';// import Jquery here    
.
.
your code
.
.
  • 并且不需要使用 const $: any = '';,您应该删除此声明。

安装jQuery

npm install --save jquery

并安装jQuery定义

npm install -D @types/jquery

** 比在这样的组件中包含 jquery **

import * as $ from jquery