前言
一般来说,Anuglar引用外部的JS或者CSS,会在index.html中引用,但是这样子会使得项目变得臃肿,对于只有某一些组件才会用到的第三方js来说,放到index根目录非常不合适。这里就拿google map举例,如何在某一组件中使用。
解决方式
在app下创建一个Component
ng g c google-map
google-map.component.ts
// 在构造函数中直接创建一个script,在运行该组件时生成到DOM中
constructor() {
const script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.defer = true;
script.src = "https://maps.googleapis.com/maps/api/js?key=自己的秘钥"; // 这里key换成自己的秘钥即可
document.body.appendChild(script);
// 在初始化函数中,监听页面加载进度,加载完成时执行内部代码(load会等待Map加载完成才会执行)
ngOnInit() {
window.addEventListener('load', (event) => {
if(typeof google !== 'undefined'){
// 执行成功就可以正常执行google map 代码了
that.map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: { lat: 22, lng: 123 }
});
} else {
alert('Google map failed to connect') // VPN没有挂上之类的,其他原因导致google map没有加载成功的提示
}
});
}
这样子操作就不用在index.html里面写google map的js引用了,完全可以正常执行google map且不会有BUG。
没有挂上VPN的报错提示
正常连接成功的样子