简体   繁体   English

如何从 JS 文件调用方法到 Angular 组件

[英]How to call a method from a JS file into an Angular component

This question doesn't have any accepted answer and also It is related to AngularJS. I need a solution for Angular. None of the answer on the inte.net is working. 这个问题没有任何可接受的答案,它也与 AngularJS 有关。我需要 Angular 的解决方案。inte.net 上的答案均无效。 My code is as follows:我的代码如下:

Columns.js列.js

export class Columns {
  getAllColumns() {
    return [
      {
        headerName: 'My Header',
        field: 'My field',
        filter: 'some filter',
        menuTabs: 'firsttab'
      },
      {...}... similar 3, 4 objects
    ]
  }

I need something like code below to assign this.fetchedCols returned columns.我需要类似下面的代码来分配this.fetchedCols返回的列。

my-component.component.ts我的组件.component.ts

...
ngOnInit() {
  this.fetchedCols = Columns.getAllColumns(); // ERROR
}

I tried these steps also from this blog :我也从这个博客尝试了这些步骤:

  • Step 1: Create a js named directory inside the assets directory and put the JavaScript (Columns.js) file inside it.第一步:在assets目录下创建一个名为js的目录,将JavaScript(Columns.js)文件放入其中。
  • Step 2: Open the index.html and add a script tag to add the JavaScript file.第二步:打开index.html,添加script标签添加JavaScript文件。
  • Step 3: Open the component where you want to use this JS file.第三步:打开你要使用这个JS文件的组件。 Add below line to declare a variable:添加以下行以声明变量:

declare var getAllColumns: any;

Use below line to call the function:使用以下线路拨打 function:

new getAllColumns();

Both the files (JS and Component) are in the same folder.这两个文件(JS 和组件)都在同一个文件夹中。 I'm getting error:我收到错误:

ERROR TypeError: this.getColumnsDefs is not a function错误类型错误:this.getColumnsDefs 不是 function

Please help.请帮忙。

You should instantiate Columns object first, try this:您应该首先实例化列 object,试试这个:

const columns = new Columns();
this.fetchedCols = columns.getAllColumns(); 

Columns object should be imported from a file where Columns is declared.应从声明列的文件中导入列 object。 But if you are using vscode or any other IDE you should be able to do that by hitting ctrl + space after Columns word但是,如果您使用的是 vscode 或任何其他 IDE,您应该可以通过在 Columns 单词后按 ctrl + space 来做到这一点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM