简体   繁体   English

如何在Angular 5中公开一个js函数

[英]how to make a js function public in angular 5

I'm using Angular 5 to develop my application. 我正在使用Angular 5开发我的应用程序。
In assets/js folder, I have a js file test.js . 在assets / js文件夹中,我有一个js文件test.js I have a variable data and a function Loaddata() in this js file. 我在这个js文件中有一个变量data和一个函数Loaddata() I want to be able to access these in my app.component.ts. 我希望能够在我的app.component.ts中访问它们。

I was able to make the variable scope public and was able to access it in component.ts, but I failed to do the same with the function. 我能够将变量作用域设为公用,并能够在component.ts中对其进行访问,但是我无法对该函数执行相同的操作。

This is the process I followed for the variable: 这是我对变量执行的过程:
1. Add reference of js file in angular-cli.json 1.在angular-cli.json添加js文件angular-cli.json

        "scripts": [
                "assets/js/test.js"
         ]

2. Added the variable name in typings.d.ts file. 2.在types.d.ts文件中添加了变量名称。

       declare var data:any;

Now I was able to access this variable in app.component.ts. 现在,我可以在app.component.ts中访问此变量。
I want to be able to access even the function in the similar manner. 我希望能够以类似的方式访问该功能。
Can anyone explain me how to do it. 谁能解释我该怎么做。

This seems like an awesome use case for using an Injectable Service. 这似乎是使用可注入服务的绝佳用例。 Create a loadData.service.ts file in the src/app directory of your application(if you are using Angular CLI), and then format it like this. 在应用程序的src / app目录中创建loadData.service.ts文件(如果使用的是Angular CLI),然后像这样格式化它。

import { Injectable } from '@angular/core';

@Injectable()
export class LoadDataService {
    data = [
        // Your Data Here
    ]
    constructor() {};

    loadData(params?) {
        // your code here
    }
}

Then, whenever you need to use that function in a component, just import the service into your component, create a local instance of it in your constructor, and then use it! 然后,每当需要在组件中使用该功能时,只需将服务导入到组件中,在构造函数中创建它的本地实例,然后使用它即可! To access the data, just set it equal to another variable in that components constructor. 要访问数据,只需将其设置为等于该组件构造函数中的另一个变量即可。

import { LoadDataService } from '../loadData.service';

@Component({
    //whatever
})

export class YourComponent {
    dataFromService: [];
    constructor(private loadDataService: LoadDataService) {
        this.dataFromService = this.loadDataService.data;
    }

    runThisToGetData() {
        this.loadDataService.loadData(yourParams).subscribe(r => r);
    }
}

Best of luck! 祝你好运!

Take a look at: https://nodejs.org/api/modules.html 看看: https : //nodejs.org/api/modules.html

You could just use exports to do what you are asking for. 您可以只使用导出来完成您所要求的。

foo.js

module.exports = {
  hello: () => alert('hello from foo!')
};

EDIT ---- Fixed syntax 编辑----固定语法

bar.js

const foo = require('./foo.js');
foo.hello();

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

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