From 588a50650f4ea042abb7b4c3721153f4ed94ce7c Mon Sep 17 00:00:00 2001 From: Kristiyan Kostadinov Date: Tue, 23 Mar 2021 16:44:27 +0100 Subject: [PATCH] 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. --- .../map-directions-service.spec.ts | 7 ++++++- .../map-directions-service.ts | 12 ++++++++---- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/src/google-maps/map-directions-renderer/map-directions-service.spec.ts b/src/google-maps/map-directions-renderer/map-directions-service.spec.ts index 6927c7e1e55d..68099a130cb0 100644 --- a/src/google-maps/map-directions-renderer/map-directions-service.spec.ts +++ b/src/google-maps/map-directions-renderer/map-directions-service.spec.ts @@ -26,7 +26,12 @@ describe('MapDirectionsService', () => { (window.google as any) = undefined; }); - it('initializes the Google Maps Directions Service', () => { + it('does not initialize the Google Maps Directions Service immediately', () => { + expect(directionsServiceConstructorSpy).not.toHaveBeenCalled(); + }); + + it('initializes the Google Maps Directions Service when `route` is called', () => { + mapDirectionsService.route({}).subscribe(); expect(directionsServiceConstructorSpy).toHaveBeenCalled(); }); diff --git a/src/google-maps/map-directions-renderer/map-directions-service.ts b/src/google-maps/map-directions-renderer/map-directions-service.ts index ec9849aa049b..7fd588a4657b 100644 --- a/src/google-maps/map-directions-renderer/map-directions-service.ts +++ b/src/google-maps/map-directions-renderer/map-directions-service.ts @@ -25,11 +25,9 @@ export interface MapDirectionsResponse { */ @Injectable({providedIn: 'root'}) export class MapDirectionsService { - private readonly _directionsService: google.maps.DirectionsService; + private _directionsService: google.maps.DirectionsService|undefined; - constructor(private readonly _ngZone: NgZone) { - this._directionsService = new google.maps.DirectionsService(); - } + constructor(private readonly _ngZone: NgZone) {} /** * See @@ -38,6 +36,12 @@ export class MapDirectionsService { */ route(request: google.maps.DirectionsRequest): Observable { return new Observable(observer => { + // Initialize the `DirectionsService` lazily since the Google Maps API may + // not have been loaded when the provider is instantiated. + if (!this._directionsService) { + this._directionsService = new google.maps.DirectionsService(); + } + const callback = ( result: google.maps.DirectionsResult|undefined,