angular4 how to call a function in a external js

2019-06-28 07:45发布

I have a jscript which displays a log to the console:

x.js contains

function open() {
    console.log('this a function');
}

in index.html of my app

<script src="x.js"></script>

in my component

declare var xJS : any;;

@Component({
   selector: 'employerfile',
   templateUrl: './employerfile.component.html'
})

export class EmployerFileComponent
    .....
    openURL() {
       xJS.open();  
    }
}

in html

<a (click)="openURL()"> click </a>

When I execute this code, I get an exception@

Original exception: xJS is not defined

How can I call this external function?

4条回答
手持菜刀,她持情操
2楼-- · 2019-06-28 08:03

You should first import it like this:

import * as xJS from 'xJS';
查看更多
Deceive 欺骗
3楼-- · 2019-06-28 08:14

You have to declare the name of the function you want to use in your angular component, as-

declare var open: any;

This basically tells the compiler that open exists somewhere, which will be then found in your js file.

Also, to use the above method in your component, you will have to use this syntax-

anyCustomMethodName/anyLifeCycleMethod() {
    new open();
}
查看更多
叼着烟拽天下
4楼-- · 2019-06-28 08:17

If your x.js file is not on your local machine or hosted on CDN or it is third-party library then you can't import it in above ways. Even System.import is deprecated.

You can add your js file into index.html and call its functions using window global object as we do earlier.

查看更多
爷的心禁止访问
5楼-- · 2019-06-28 08:21

Importing your file like this <script src="x.js"></script> will not work.

You have to import it in the following way:

import * as xJS from './x.js';

If it will not work, the alternative way is to use System.import:

declare var System: any; 

System.import('./x.js')
    .then(xJS => {
        xJS.open();
    });

You can check the following SO post.

查看更多
登录 后发表回答