Skip to content

Commit 588a506

Browse files
authored
fix(google-maps): initialize directions service lazily (#22302)
Similar to #22159. Only initializes the Google Maps `DirectivesService` when calling `route`, because doing so in the constructor might be too early.
1 parent b994349 commit 588a506

File tree

2 files changed

+14
-5
lines changed

2 files changed

+14
-5
lines changed

src/google-maps/map-directions-renderer/map-directions-service.spec.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,12 @@ describe('MapDirectionsService', () => {
2626
(window.google as any) = undefined;
2727
});
2828

29-
it('initializes the Google Maps Directions Service', () => {
29+
it('does not initialize the Google Maps Directions Service immediately', () => {
30+
expect(directionsServiceConstructorSpy).not.toHaveBeenCalled();
31+
});
32+
33+
it('initializes the Google Maps Directions Service when `route` is called', () => {
34+
mapDirectionsService.route({}).subscribe();
3035
expect(directionsServiceConstructorSpy).toHaveBeenCalled();
3136
});
3237

src/google-maps/map-directions-renderer/map-directions-service.ts

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,9 @@ export interface MapDirectionsResponse {
2525
*/
2626
@Injectable({providedIn: 'root'})
2727
export class MapDirectionsService {
28-
private readonly _directionsService: google.maps.DirectionsService;
28+
private _directionsService: google.maps.DirectionsService|undefined;
2929

30-
constructor(private readonly _ngZone: NgZone) {
31-
this._directionsService = new google.maps.DirectionsService();
32-
}
30+
constructor(private readonly _ngZone: NgZone) {}
3331

3432
/**
3533
* See
@@ -38,6 +36,12 @@ export class MapDirectionsService {
3836
*/
3937
route(request: google.maps.DirectionsRequest): Observable<MapDirectionsResponse> {
4038
return new Observable(observer => {
39+
// Initialize the `DirectionsService` lazily since the Google Maps API may
40+
// not have been loaded when the provider is instantiated.
41+
if (!this._directionsService) {
42+
this._directionsService = new google.maps.DirectionsService();
43+
}
44+
4145
const callback =
4246
(
4347
result: google.maps.DirectionsResult|undefined,

0 commit comments

Comments
 (0)