我按照官方文档中所述成功实现了Angular内置的Google Maps组件的延迟加载:https://github.com/angular/components/tree/master/src/google-maps
export class GoogleMapsDemoComponent {
apiLoaded: Observable<boolean>;
geoCoder: any;
constructor(httpClient: HttpClient) {
this.apiLoaded = httpClient.jsonp('https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_HERE', 'callback')
.pipe(
map(() => true),
catchError(() => of(false)),
);
}
ngOnInit(): void {
this.apiLoaded.subscribe(() => this.initGeoCoder());
}
initGeoCoder() {
this.geoCoder = new google.maps.Geocoder();
}
}
但是,如果组件被多次初始化,我现在会遇到错误。
You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors.
我想把加载Google脚本的任务放到一个专门的服务中,并将其注入到所有需要它的组件中。
Github仓库中的讨论确认了这种方法:
你应该可以将httpClient.jsonp('https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_HERE','callback')和周围的API加载重构为一个服务,以便它可以充当单例并防止多个加载。请注意,您需要在@Injectable中添加providedIn:'root',以使它不会为每个模块创建实例,从而为每个实例加载API。
然而,我没能很好地完成这个任务,我一直收到以下错误信息,似乎是在Google脚本尚未加载时引发的:
ERROR ReferenceError: google is not defined
服务:
export class GeoService {
apiLoaded: Observable<boolean>;
constructor(private http: HttpClient) {
this.apiLoaded = this.http
.jsonp(
'https://maps.googleapis.com/maps/api/js?key=API_KEY',
'callback'
)
.pipe(
map(() => true),
catchError((error) => of(error))
);
}
}
组件:
export class GoogleMapsDemoComponent {
apiLoaded: Observable<boolean>;
geoCoder: any;
constructor(geo: GeoService) {}
ngOnInit(): void {
this.geo.apiLoaded.subscribe(() => this.initGeoCoder());
}
initGeoCoder() {
this.geoCoder = new google.maps.Geocoder();
}
}
我的服务在一个共享模块中,它被导入到组件的模块中。我也尝试在同一模块内使用服务,以确保我没有弄错导入,但是我收到了相同的错误信息。
有人可以告诉我我漏掉了什么吗?