Skip to content

Commit

Permalink
fix(google-maps): initialize directions service lazily (angular#22302)
Browse files Browse the repository at this point in the history
Similar to angular#22159. Only initializes the Google Maps `DirectivesService` when calling `route`, because doing so in the constructor might be too early.
  • Loading branch information
crisbeto authored Mar 23, 2021
1 parent b994349 commit 588a506
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -38,6 +36,12 @@ export class MapDirectionsService {
*/
route(request: google.maps.DirectionsRequest): Observable<MapDirectionsResponse> {
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,
Expand Down

0 comments on commit 588a506

Please sign in to comment.