我用 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/