【发布时间】:2018-03-24 09:39:58
【问题描述】:
我正在为一个 Angular 应用程序输入 @typings/googlemaps,该应用程序在运行时不会返回任何警告或错误。
但是,我想为我的组件创建一些单元测试,但 Karma 无法启动,产生如下错误:
ERROR in: ... Cannot find namespace 'google'.
我关注this post 和其他喜欢它的人来安装打字并继续我的工作。
将declare var google:any 添加到 typings.d.ts 将不起作用,因为它已经在类型文件中声明,并且给出了“重复标识符”编译错误。
有什么建议吗?
编辑 1:
我的 google-maps.service.ts 上的代码摘录,其中一个文件给出了错误。我不导入 googlemaps,因为它不是必需的,因为它是我理解的打字。
import {Injectable} from "@angular/core";
import {environment} from "../../../environments/environment";
import {Http} from "@angular/http";
import {forEach} from "@angular/router/src/utils/collection";
@Injectable()
export class GoogleMapsService {
scriptLoadingPromise: Promise<void>;
api_key = '';
url = '';
map: google.maps.Map;
markers: Array<google.maps.Marker>;
bounds: google.maps.LatLngBounds;
geocoder: google.maps.Geocoder;
constructor(private http: Http) {
this.api_key = '1234';
this.url = 'https://maps.googleapis.com/maps/api/js';
this.markers = new Array();
// Loading script
this.load().then(() => {
this.geocoder = new google.maps.Geocoder();
});
}
}
getScriptSrc(callbackName: string): string {
return `https://maps.googleapis.com/maps/api/js?key=${this.api_key}&callback=${callbackName}`;
};
onReady(): Promise<void> {
return this.scriptLoadingPromise;
};
load(): Promise<void> {
if (this.scriptLoadingPromise) {
return this.scriptLoadingPromise;
}
const script = window.document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.defer = true;
const callbackName = 'googleMapsServiceCallback';
script.src = this.getScriptSrc(callbackName);
this.scriptLoadingPromise = new Promise<void>((resolve: Function, reject: Function) => {
(<any>window)[callbackName] = () => {
resolve();
};
script.onerror = (error: Event) => {
reject(error);
};
});
window.document.body.appendChild(script);
return this.scriptLoadingPromise;
}
编辑 2:我更新了上面的代码。它使用与Angular 2+ Maps 项目相同的结构,参考code here。由于键入时考虑了“google”关键字,因此没有引发任何预编译错误。
【问题讨论】:
-
您能否分享您的代码 - 例如,在生成此错误的文件中,您是否有 googlemaps 的导入?
-
@Fenton - 添加了一些代码
标签: angular google-maps unit-testing typescript