我正在嘗試使用@angular/google-maps。
一切正常,但我在瀏覽器上不斷收到以下錯誤:
“您已在此頁面上多次包含 Google Maps JavaScript API。這可能會導致意外錯誤。”
我正在嘗試延遲加載 API。
"@angular/animations": "~13.3.0",
"@angular/common": "~13.3.0",
"@angular/compiler": "~13.3.0",
"@angular/core": "~13.3.0",
"@angular/forms": "~13.3.0",
"@angular/google-maps": "^13.3.9",
我有一個共享地圖組件,供其他組件使用。
所以在這個組件中,我嘗試了檔案中所說的 ( documentation ):
export class MapComponent {
apiLoaded: Observable<boolean>;
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)),
);
}
...
}
這種方法導致了錯誤。每次使用此組件時,都會呼叫建構式,然后再次加載 API。
所以我嘗試在單例服務上這樣做,如下所示:
@Injectable({
providedIn: 'root'
})
export class MapServiceService {
apiLoaded!: Observable<boolean>;
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)),
);
}
isApiLoaded(): Observable<boolean> {
return this.apiLoaded;
}
}
然后在組件上我這樣做:
export class MapComponent implements OnInit {
options!: google.maps.MapOptions;
apiLoaded!: Observable<boolean>;
constructor(private _mapService: MapServiceService) {
}
ngOnInit(): void {
this.apiLoaded = this._mapService.isApiLoaded();
}
...
我可以看到現在服務的建構式被呼叫了一次,但我仍然收到該錯誤。
正確的方法是什么?
謝謝閱讀!
uj5u.com熱心網友回復:
問題在于呼叫可觀察到的 apiLoaded。
在用戶界面中,我正在執行以下操作:
<div *ngIf="apiLoaded | async">
<google-map height="500px" width="100%" [options]="options"></google-map>
</div>
基本上,我訂閱了 isApiLoaded() 方法,該方法最終會在我每次呈現組件時嘗試加載 API。
這是我的解決方案:
export class MapServiceService {
private currentApiStatus: BehaviorSubject<Boolean>;
obsCurrentApiStatus: Observable<Boolean>;
constructor(httpClient: HttpClient) {
this.currentApiStatus = new BehaviorSubject(new Boolean(false));
this.obsCurrentApiStatus = this.currentApiStatus.asObservable();
httpClient.jsonp('https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_HERE', 'callback')
.pipe(
map(() => true),
catchError(() => of(false)),
).subscribe( loaded => {
this.currentApiStatus.next(loaded);
});
}
}
然后在組件上:
apiLoaded!: boolean;
constructor(private _mapService: MapServiceService) {
}
ngOnInit(): void {
this._mapService.obsCurrentApiStatus.subscribe(status => {
this.apiLoaded = status.valueOf();
});
...
在用戶界面中:
<div *ngIf="apiLoaded">
<google-map height="500px" width="100%" [options]="options"></google-map>
</div>
我希望這能為某人節省時間,如果您知道更好的實作方法,我愿意學習!
謝謝!
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/533864.html
標籤:有角度的谷歌地图延迟加载
