2017-06-16 71 views
0

我已经编写了一个js文件来返回一些值到我的角度项目中的ts文件。想要从js文件访问外部变量到角度2 ts文件

var webGlObject = (function() { 
    return { 
    init: function() { 
     alert('webGlObject initialized'); 
    } 
    } 
})(webGlObject||{}) 
import { Component, OnInit } from '@angular/core'; 
import '../../../lib/jquery-3.2.1.min.js'; 
import '../../../server/getSummary.js'; 

declare var webGlObject: any; 

@Component({ 
    selector: 'mop-designer-dashboard', 
    templateUrl: 'mop-designer-dashboard.component.html', 
    styleUrls: ['mop-designer-dashboard.component.css'], 
}) 

export class MopDesignerDashboardComponent implements OnInit { 

    debugger; 
    scoreBoardList: any = []; 
    breadcrumb: any = []; 

    constructor() { 

    /* prepare breadcrumb */ 
    this.breadcrumb = [ 
     { 
     label: 'Mop Designer', 
     href: '/#/mop-designer' 
     } 
    ]; 

    debugger; 

    webGlObject.init(); 



    } 

    ngOnInit() { 
    console.log('test'); 
    } 
} 

但声明VAR webGlObject:任;不会创建任何对象 ,我得到以下错误:

> ZoneTask.invoke @ zone.js FAD3:339 VM292602:61错误:未捕获的(在承诺):错误:错误:0:0致:webGlObject没有定义 的ReferenceError:webGlObject没有在新MopDesignerDashboardComponent

回答

0

这是因为你创建它作为一个类和使用作为一个对象定义 。 试试这个: 放在js文件如下:

var webGlObject = function() { 
this.init= function() { 
    alert('webGlObject initialized');}} 

而在TS文件创建一个实例:

declare var webGlObject: any; 
export class YourComponent{ 
constructor(){ 
    let wegObj = new webGlObject(); 
    wegObj.init(); 
    } 
}