【问题标题】:On calling JavaScript file from Angular 2 project从 Angular 2 项目调用 JavaScript 文件
【发布时间】:2017-03-28 14:39:31
【问题描述】:

我用 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);

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

【问题讨论】:

    标签: javascript jquery angular getscript


    【解决方案1】:
        $.getScript('./app/calendar/zapCalendar.js', function(){
            console.log("got call'd back");
            this.myCal = new CustomCal(2017);
        });
    

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

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

    【讨论】:

    • 谢谢你,我不知道这一点(角度新手)。但是,虽然我的这个引用现在可能是正确的,但我仍然收到未定义 CustomCal 的错误(在控制台中)。
    【解决方案2】:

    您需要导出类,然后将其导入您的组件中

    import {CustomCal} from "./app/calendar/zapCalendar";
    

    【讨论】:

    • 我不熟悉编写模块。当我在 CustomCal 类之前使用 export 关键字并尝试导入时,我收到消息“找不到模块 './zapCalendar'。)”
    • 应该有文件./app/calendar/zapCalendar.ts
    • .ts?但我的 zapCalendar 是一个 javascript 文件。
    • 我的印象是我需要在 typescript/angular2 中重写我的日历 ctrl。不赞成使用 jquery 吗?
    • 请注意,Typescript 是它自己的东西。你可以写一个 Typescript 文件,它可以与 Angular 无关。由于您的代码只是一个类,因此不需要大量的移植工作即可将其解析为 Typescript。
    猜你喜欢
    • 2017-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-08
    • 2019-03-02
    • 2017-04-19
    • 1970-01-01
    • 2017-07-10
    相关资源
    最近更新 更多