错误TS2503:找不到名称空间"google".角度7 [英] error TS2503: Cannot find namespace 'google'. Angular-7
问题描述
我在我的角度应用程序中将google放置为自动完成搜索功能,当我运行该应用程序时,cli给出了该错误消息.
I'm make google place Autocomplete search function in my angular application, when i was run the application, cli was give that error message.
角度cli版本-7.3.8
angular cli version - 7.3.8
import { GooglePlaceModule } from "ngx-google-places-autocomplete";
import { AgmCoreModule } from '@agm/core';
google-place.components.ts
declare const google: any;
import { MapsAPILoader } from '@agm/core';
public latitude: number;
public longitude: number;
public searchControl: FormControl;
public zoom: number;
constructor(
private mapsAPILoader: MapsAPILoader,
private ngZone: NgZone
) { }
ngOnInit() {
// map script start==========================================
//set google maps defaults
this.zoom = 12;
this.latitude =6.7370647;
this.longitude =79.93713920000005;
//create search FormControl
this.searchControl = new FormControl();
//set current position
this.setCurrentPosition();
//load Places Autocomplete
this.mapsAPILoader.load().then(() => {
let autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement);
autocomplete.addListener("place_changed", () => {
this.ngZone.run(() => {
//get the place result
let place: google.maps.places.PlaceResult = autocomplete.getPlace();
//verify result
if (place.geometry === undefined || place.geometry === null) {
return;
}
//set latitude, longitude and zoom
this.latitude = place.geometry.location.lat();
this.longitude = place.geometry.location.lng();
this.zoom = 12;
console.log("lat--> "+ this.latitude +" lon-->"+ this.longitude);
});
});
});
// map script end==========================================
}
tsconfig.json
{
.........."
],
"types": ["googlemaps"]
}
}
错误TS2503:找不到名称空间"google".
error TS2503: Cannot find namespace 'google'.
推荐答案
您应该在组件( google-place.components.ts
)中将google声明为环境:
you should declare google as ambient in your component (google-place.components.ts
):
// Declare google ambient
declare var google: any;
环境声明 是一种告诉 TypeScript 编译器,实际的源代码存在于其他位置....为了确保类型安全和智能,Ambient声明有助于将其他js库无缝集成到TypeScript中.
Ambient declarations are a way of telling the TypeScript compiler that the actual source code exists elsewhere. ... Ensuring typesafety and intellisense, Ambient declarations help to seamlessly integrate other js libraries into TypeScript.
您还需要向项目添加相应的依赖项和类型.这些就是这些.
You also need to add corresponding dependencies and types to your project. So these are.
-> 类型":[..."googlemaps"]
在package.json中-> "dependencies":[..."googlemaps ::" ^ 1.12.0]
in package.json -> "dependencies":[... "googlemaps": "^1.12.0"]
从Google地图获取密钥,然后将该密钥放置在 @NgModule
Get key from google maps and then place that key in app.module.ts under @NgModule
AgmCoreModule.forRoot({
apiKey: 'your key generated from google maps'
});
这篇关于错误TS2503:找不到名称空间"google".角度7的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!