javascript - Angular2 在组件内部调用外部 JS 文件函数

标签 javascript angular typescript angular2-components

抱歉,如果这个问题是重复的。我无法在网上找到任何合适的解决方案,所以我在这里发帖。

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

请帮我解决这个问题。

最佳答案

这应该在 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));
}

关于javascript - Angular2 在组件内部调用外部 JS 文件函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40908940/

相关文章:

javascript - 如何将变量放置在指令 HTML block 内并让 Controller 访问它?

Angular/RxJS : synchronous observable

css - 不是全局更改 ionic 搜索栏的占位符和清除图标颜色?

typescript - 函数应该返回 Promise<string>,显然返回 Promise<unknown> 但仍然可以编译

javascript - 从 url 下载 Pdf,将其保存在文件中,zip 然后下载 zip

javascript - LowDB获取具有最高时间戳的对象

angular - 如何以 Angular 8 显示文件

typescript - 我将如何测试在 Node.js 中使用命名空间的 Typescript 代码?

reactjs - ForkTsCheckerWebpackPlugin内存不足(解决方案)

javascript - 我可以循环遍历数据表列对象并添加+2的新行添加吗