ngx-script-loader
ngx-script-loader copied to clipboard
Handling callback url parameter
Google Maps JS SDK uses that approach
<div id="map"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
async defer></script>
Script url accepts a callback
parameter as a global function name to trigger it after Google Maps SDK is ready.
So, we need a solution to automate that process.
I have a proposal:
const request = {
url: 'https://maps.googleapis.com/maps/api/js',
queryParams: {
key: 'API_KEY',
callback: () => {
// Google maps ready
}
}
}
this.scriptService.loadScript(request)
.subscribe(() => {});
So first parameter of loadScript
could get a simple string url or a Request
object that will have url
and queryParams
properties.
more general question than mentioned here, but it can be handy.
in the official angular google maps lib, they use http.jsonp
method to load script lazily programmatically and this jsonp
method accepts callback name
https://github.com/angular/components/blob/main/src/google-maps/README.md
// google-maps-demo.component.ts
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
@Component({
selector: 'google-maps-demo',
templateUrl: './google-maps-demo.component.html',
})
export class GoogleMapsDemoComponent {
apiLoaded: Observable<boolean>;
constructor(httpClient: HttpClient) {
// If you're using the `<map-heatmap-layer>` directive, you also have to include the `visualization` library
// when loading the Google Maps API. To do so, you can add `&libraries=visualization` to the script URL:
// https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=visualization
this.apiLoaded = httpClient.jsonp('https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_HERE', 'callback')
.pipe(
map(() => true),
catchError(() => of(false)),
);
}
}