2017-06-16 73 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(); 
    } 
}