Angular 5/谷歌地图 - "ReferenceError: google is not defined"

标签 angular google-maps undefined markerclusterer

我将 Angular 5 与一种类型一起使用:“@types/markerclustererplus”:“2.1.28”。这种类型安装@types/google-maps。

我在“index.html”文件中添加了脚本部分来加载 map 。 在我的组件中,我可以使用 google 命名空间。 这很好用。

但是,当我运行测试时...它失败了! 我收到“ReferenceError: google is not defined”

我尝试了很多东西...如果您有任何想法,我接受!

谢谢。

最佳答案

在您的测试中,您可以使用模拟/ stub 在 window 对象以及您的组件与之交互的任何其他对象/函数上定义 google:

window['google'] = {
  maps: {
    Maps: () => {}
  }
};

然后您可以使用 using Jasmine Spies拦截对 google 上给定对象和/或函数的调用,例如 maps 以返回自定义值或测试组件所需的任何其他内容。

const spy = spyOn(window['google']['maps'], 'Maps').and.returnValue({});

使用括号表示法来取悦 TypeScript 编译器的原因。使用点符号,您会看到诸如 Property 'google' does not exist on type 'Window' 之类的错误。

希望这至少有助于解决您看到的未定义错误。

谢谢!

关于Angular 5/谷歌地图 - "ReferenceError: google is not defined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48266942/

相关文章:

javascript - Angular 5. 如何跟踪 Javascript 文件中的路由更改,或在组件级别执行功能?

angular - RxJS 6 页面不活动时暂停或缓冲可观察

angular - 使用纯 CSS 更改 Material 2 中的单选按钮颜色

angular - ReactJs 是否有像 Angular 4.0 那样的 AOT?

具有谷歌地图 View 的 iOS 应用程序未触发 TouchEnded :withEvent: method

android - 模块根文件夹中缺少文件 google-services.json(但它在好地方!)

javascript - 将字符串数组值转换为数组对象

javascript - node-mysql connection.query() 返回未定义

javascript - 其他语言中是否有类似的 "undefined"概念?

Javascript : Function parameter is undefined