javascript - 从 Angular 2 项目调用 JavaScript 文件

标签 javascript jquery angular getscript

我用 jQuery 编写了一个日历控件,我想在 Angular 2 项目中使用它。

我从有关此主题的其他答案中了解到,我可以使用 jQuery 的 getScript() API 调用外部 JavaScript 文件。

我的calendar.component.ts看起来像这样:

import { Component, OnInit, AfterViewInit }     from '@angular/core';
import { Auth }                                 from '../auth.service';

declare var $:any;
declare var CustomCal:any;

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

    private year : number;
    myCal : any;

    constructor(private auth : Auth) {
    }

    ngOnInit() {
    }

    ngAfterViewInit() {
        this.year   = 2017;

        $.getScript('./app/calendar/zapCalendar.js', function(){
            console.log("got call'd back");
            this.myCal = new CustomCal(2017);
        });
    }
}

我收到控制台消息“已回电”,然后收到一条错误消息,指出 CustomCal 未定义。

我的 CustomCal 类在 zapCalendar.js 中定义如下:

class CustomCal
{
    constructor(nYear) {

        this._mouseDown     = false;
        this._mouseDrag     = false;

        this._lastItem      = 0;
        this._nYear         = nYear;

        this.CreateCalendarFrame();
        this.AddEventHandlers(this);
    }

    ...
}

我尝试导出 zapCalendar.js 文件中的类,并尝试将以下内容添加到 zapCalendar.js 文件中:

$( function() {
    var myCal = new CustomCal(2017);
});

我在这里缺少什么?

更新:

我刚刚替换了这个(在 zapCalendar.js 中)

$( function() {
    var myCal = new CustomCal(2017);
});

这样:

var x = new CustomCal(2017);

现在日历可以正确呈现。但我想(如果可能的话)在我的 typescript 中获得对日历的引用。这可能吗?

最佳答案

    $.getScript('./app/calendar/zapCalendar.js', function(){
        console.log("got call'd back");
        this.myCal = new CustomCal(2017);
    });

此处的内部函数不会具有相同的 this 引用,因为它不会被绑定(bind)到您的对象进行调用。由于您使用的是 TypeScript,因此只需使用箭头函数即可更改此行为。

    $.getScript('./app/calendar/zapCalendar.js', () => {
        console.log("got call'd back");
        this.myCal = new CustomCal(2017);
    });

关于javascript - 从 Angular 2 项目调用 JavaScript 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43072545/

相关文章:

javascript - 放大时网页方向发生变化

javascript - 为什么馅饼的颜色没有改变?

javascript - 如何通过 PHP 填充 Bootstrap 弹出窗口

angular - 如何在Angular HTTP中获得临时响应-ArrayBuffer

angular - 检查一个值是私有(private)的还是只读的

javascript - 使用另一个值数组设置复选框值数组

javascript - Gmail 插件使用文本输入创建单选组

javascript - 我应该把 jQuery 脚本标签放在哪里?

php - 如何在 yii2 中动态加载内容中加载小部件?

angular - 尽管有 OnPush 策略,为什么 Angular 会在 DOM 事件的父组件上触发 ChangeDetection?