如何从角组件中的url加载外部js文件?
具体来说,我正在尝试将google-maps-api加载到我的角度项目中。目前,我在我的index.html中这样做:
<script async defer src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=initMap">
</script>注意:我知道angular-maps。这不是一个选择。
发布于 2018-01-07 06:50:15
一个解决方案是在ngAfterViewInit()中动态创建脚本标记
import { DOCUMENT } from '@angular/common';
...
constructor(private @Inject(DOCUMENT) document,
private elementRef:ElementRef) {};
ngAfterViewInit() {
var s = this.document.createElement("script");
s.type = "text/javascript";
s.src = "https://maps.googleapis.com/maps/api/js?key=API_KEY";
this.elementRef.nativeElement.appendChild(s);
}另见https://github.com/angular/angular/issues/4903
更新
<div id="map" #mapRef></div>export class GoogleComponent implements OnInit {
@ViewChild("mapRef") mapRef: ElementRef;
constructor() { }
ngOnInit() {
this.showMap();
}
showMap() {
console.log(this.mapRef.nativeElement);
const location = { lat: 28.5355, lng: 77.3910 };
var options = {
center: location,
zoom: 8
}
const map = new google.maps.Map(this.mapRef.nativeElement, options);
this.addMarket(map, location);
}
addMarket(pos, map) {
return new google.maps.Marker({
position: pos,
map: map,
});
}
}发布于 2018-02-20 01:16:23
您可以在任何需要的时候使用承诺异步加载google。
// map-loader.service.ts
import ...
declare var window: any;
@Injectable()
export class MapLoader {
private static promise;
map: google.maps.Map;
public static load() {
if (!MapLoader.promise) { // load once
MapLoader.promise = new Promise((resolve) => {
window['__onGapiLoaded'] = (ev) => {
console.log('gapi loaded')
resolve(window.gapi);
}
console.log('loading..')
const node = document.createElement('script');
node.src = 'https://maps.googleapis.com/maps/api/js?key=<YOUR _API_KEY>&callback=__onGapiLoaded';
node.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(node);
});
}
return MapLoader.promise;
}
initMap(gmapElement, lat, lng) {
return MapLoader.load().then((gapi) => {
this.map = new google.maps.Map(gmapElement.nativeElement, {
center: new google.maps.LatLng(lat, lng),
zoom: 12
});
});
}
}组件
//maps.component.ts
...
@Component({
selector: 'maps-page',
templateUrl: './maps.component.html'
})
export class MapsComponent implements OnInit {
@ViewChild('gmap') gmapElement: any;
constructor(public mapLoader: MapLoader) { }
ngOnInit() {
this.mapLoader.initMap(this.gmapElement, -37.81, 144.96) // await until gapi load
}
...
}组件HTML
// maps.component.html
<div #gmap ></div>不要忘记将CSS添加到元素中。
https://stackoverflow.com/questions/48134937
复制相似问题