【问题标题】:Angular2 Call External JS file Function Inside the ComponentsAngular2 在组件内部调用外部 JS 文件函数
【发布时间】:2016-12-01 11:02:07
【问题描述】:

对不起,如果这个问题是重复的。我仍然无法在网络上找到任何合适的解决方案,所以我在这里发布。

我在 Angular 2 中创建一个组件。我有一个外部 js 文件并动态加载它。在外部 js 文件中,我有一个带参数的函数。如何在ngAfterViewInit 中调用该参数。我是 Angular 2 的新手,所以不知道如何在 Angular 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>

请帮我解决这个问题。

【问题讨论】:

    标签: javascript angular typescript angular2-components


    【解决方案1】:

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

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

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

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

    或者属性 typescript 的方式,声明函数,这个可以放在你的源文件夹中任何名为.d.ts的文件中:

    declare function message(msg: string) : void;
    

    也见this question

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

    在役:

    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));
    }
    

    【讨论】:

    • 能否请您更正我的属性 typescript 方式的代码,我无法得到您
    • 抱歉不工作
    • 你给的问题链接不相关,是从两个.ts文件导入函数而不是从.js到.ts文件的导入希望你理解
    • 它实际上是一样的。打字稿编译为 javascript,声明所做的只是使它,因此打字稿编译器知道该函数存在于 javascript 引擎中的某个地方。它可能在另一个打字稿文件(编译为 javascript)中,在你的情况下的 javascript 文件中,或者由浏览器提供。它只是让 typescript 编译器知道该函数存在于某个地方。
    猜你喜欢
    • 2016-06-25
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-02
    • 2021-09-23
    相关资源
    最近更新 更多