admin管理员组文章数量:1220500
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: './employerfileponent.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?
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?
Share Improve this question edited Sep 26, 2018 at 14:17 Hristo Eftimov 15.7k14 gold badges54 silver badges79 bronze badges asked Jun 19, 2017 at 6:12 FlorenceFlorence 1,7213 gold badges14 silver badges23 bronze badges4 Answers
Reset to default 6Importing 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.
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();
}
You should first import it like this:
import * as xJS from 'xJS';
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.
本文标签: javascriptangular4 how to call a function in a external jsStack Overflow
版权声明:本文标题:javascript - angular4 how to call a function in a external js - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1739345895a2159160.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论