Angular2 找不到命名空间“google" [英] Angular2 Cannot find namespace 'google'
问题描述
我正在使用 angular2-google-maps
和最新版本的 Angular2.我正在尝试将一些本地地图组件功能转换为它们自己的文件 maps.service.ts
中的服务.例如:
I am working with angular2-google-maps
and latest version of Angular2. I am trying to convert some of the local map component functions into services in their own file maps.service.ts
. For example:
map.component.ts
map.component.ts
getGeoLocation(lat: number, lng: number) {
if (navigator.geolocation) {
let geocoder = new google.maps.Geocoder();
let latlng = new google.maps.LatLng(lat, lng);
let request = { latLng: latlng };
geocoder.geocode(request, (results, status) => {
if (status == google.maps.GeocoderStatus.OK) {
let result = results[0];
if (result != null) {
this.fillInputs(result.formatted_address);
} else {
alert("No address available!");
}
}
});
}
}
变成类似:maps.service.ts
getGeoLocation(lat: number, lng: number): Observable<google.maps.GeocoderResult[]> {
let geocoder = new google.maps.Geocoder();
let latlng = new google.maps.LatLng(lat, lng);
let request = { latLng: latlng };
return new Observable((observer: Observer<google.maps.GeocoderResult[]>) => {
geocoder.geocode({ request }, (
(results: google.maps.GeocoderResult[], status: google.maps.GeocoderStatus) => {
if (status == google.maps.GeocoderStatus.OK) {
observer.next(results);
observer.complete();
} else {
console.log('Geocoding service failed due to: ' +status);
observer.error(status);
}
}
));
});
}
我遇到的问题是,当我尝试使用 Observer<google.maps.GeocoderResult[]>
时,无法识别 google
变量.我在服务类之外也有 declare var google: any;
.
The issue I'm getting is that google
variable is not being recognized when I try to use Observer<google.maps.GeocoderResult[]>
. I have declare var google: any;
outside of the service class as well.
google
变量在我的 map.componenet.ts
中有效,但在 maps.service.ts
中无法识别.
The google
variable works in my map.componenet.ts
but doesn't get recognized in the maps.service.ts
.
推荐答案
Angular 6 &7 个步骤(也应该适用于所有其他 Angular 版本):
npm install @types/googlemaps --save-dev
- 分别在
tsconfig.spec.json
中将googlemaps添加到 - 重启 npm 服务器
tsconfig.app.json
中的types数组中最后应该是这样的:
您可以从组件中删除两种声明类型:import {} from '@types/googlemaps';
declare var google: any;
您不必包括其中任何一个.
You can delete both declaration types from the components:
import {} from '@types/googlemaps';
declare var google: any;
You don't have to include any of them.
PS:如果您使用 agm-s GoogleMapsAPIWrapper.getNativeMap(),您必须在使用之前转换地图对象.例如打开流量层:
PS: If you are using agm-s GoogleMapsAPIWrapper.getNativeMap() you must convert the map object before you use it. For example turning on the traffic layer:
this.apiWrapper.getNativeMap().then(map => {
this.trafficLayer = new google.maps.TrafficLayer();
const gMap: any = map;
this.trafficLayer.setMap(gMap as google.maps.Map);
});
这篇关于Angular2 找不到命名空间“google"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!