2016-12-01 124 views
5

对不起,如果这个问题是重复的家伙。我无法找到任何合适的解决方案,所以我在这里发布。Angular2调用外部JS文件函数里面的组件

我正在角2创建一个组件。我有一个外部js文件并动态加载它。在外部的js文件中,我有一个带参数的函数。如何在ngAfterViewInit内调用该参数。我是新来的角2,所以不知道怎么称呼在角2打字稿的js函数,我会后我的代码,供大家参考

app.component.ts

import { Component, OnInit, ElementRef,AfterViewInit } from '@angular/core'; 
declare var $:any; 
@Component({ 
    selector: 'app-root', 
    template: '<div></div>' 
}) 

export class AppComponent implements AfterViewInit { 
urlinput; 
    constructor(elRef: ElementRef){ 
    this.urlinput = elRef.nativeElement.getAttribute('urlinput'); 
    this.loadScript(); 
    } 
    ngAfterViewInit() { 
    // need to call the js function here 
    //tried like this initializeDataTable(this.urlinput) not worked 
    } 

loadScript() { 
    var head = document.getElementsByTagName('head')[0]; 
    var script = document.createElement('script'); 
    script.type = 'text/javascript'; 
    script.src = "app/Message.js"; 
    head.appendChild(script); 
} 
} 

Message.js(外部JS文件)

function initializeDataTable(dTableURL){ 
     $.ajax({ 
       "url": dTableURL, 
       "success": function(json) { 
        var tableHeaders; 
        $.each(json.columns, function(i, val){ 
         tableHeaders += "<th>" + val + "</th>"; 
        }); 
        $("#tableDiv").empty(); 
        $("#tableDiv").append('<table id="displayTable" class="display" cellspacing="0" width="100%"><thead><tr>' + tableHeaders + '</tr></thead></table>'); 
        $('#displayTable').dataTable(json); 
       }, 
        "dataType": "json" 
     }); 
    } 

的index.html

<app-root urlinput="app/array.txt">Loading...</app-root> 

请帮我解决这个问题。

回答

2

这应该在window对象上创建一个message属性。由于窗口对象是一些定义文件可能声明,你可以这样做:

window['message']('Hello, world!') 

或者将其设置为一个变量,并使用它:

var message: any = window['message']; 
message('Hello, world!'); 

或属性打字稿的方式,声明函数这可以走在你的源文件夹命名为.d.ts的任何文件:

declare function message(msg: string) : void; 

this question了。

动态加载脚本的问题在于,您无法确定在执行代码时加载了脚本。您可能应该使用message(msg: string)方法创建服务。该服务的构造函数可以创建脚本标记(并检查是否已经存在,如果不是单例),并在脚本加载后处理它们时排队消息。检测脚本的加载没有完整的跨浏览器支持,所以你可以做一些像谷歌分析一样的东西,并设置一些全局窗口属性,你的外部脚本将在最后调用处理任何未决消息:

In服务:

constructor() { 
    if (!window['message']) { 
    window['message'] = function(msg) { 
     window['messagequeue'] = window['messagequeue'] || []; 
     window['messagequeue'].push(msg); 
    } 
    } 
    // add script tag to load script 
} 

message(msg) { 
    window['message'](msg); 
} 

在你的脚本:

function message(msg) { 
    console.log(msg) 
    //logics goes here 
} 

// process messages queued before script loaded 
if (window['messagequeue']) { 
    window['messagequeue'].forEach(msg => message(msg)); 
} 
+0

能否请您纠正我的财产打字稿方式代码,我能不能让你 –

+0

遗憾没工作 –

+0

的问题,你给了链接ñ与此相关,它是从两个.ts文件导入函数,而不是从.js导入.ts文件,希望你能理解 –