Javascript 在Angular 7中动态更改agm地图google地图API键
我正在构建一个应用程序,让你编辑地图,编辑器有谷歌地图与Agm地图模块,最终的结果是一个iframe与他的地图嵌入到他的网页。 我将模块用于编辑器,并在app.module.ts中使用API密钥导入它Javascript 在Angular 7中动态更改agm地图google地图API键,javascript,angular,google-maps,agm,agm-map,Javascript,Angular,Google Maps,Agm,Agm Map,我正在构建一个应用程序,让你编辑地图,编辑器有谷歌地图与Agm地图模块,最终的结果是一个iframe与他的地图嵌入到他的网页。 我将模块用于编辑器,并在app.module.ts中使用API密钥导入它 import { AgmCoreModule } from '@agm/core'; ... imports: [ ... AgmCoreModule.forRoot({ apiKey: 'YOUR_KEY' }) ] iframe将是一个单独的angular应用程序,使用相同的后端
import { AgmCoreModule } from '@agm/core';
...
imports: [
...
AgmCoreModule.forRoot({
apiKey: 'YOUR_KEY'
})
]
iframe将是一个单独的angular应用程序,使用相同的后端。我需要从数据库中获取用户的API密钥,但我无法了解如何以Angular方式构建此部分,它似乎使用API密钥创建构建,是否可以在运行时修改密钥?我已经在jQuery中看到了这一点。可以从脚本标记中的代码或vanilla js中获取,例如:
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
在最后一个例子中,它可以很容易地完成,
谢谢我确实马上解决了它,在我的例子中,我用这段代码从API获得了密钥
import { AgmCoreModule, LAZY_MAPS_API_CONFIG, LazyMapsAPILoaderConfigLiteral }
from '@agm/core';
export function agmConfigFactory(http: HttpClient, config: LazyMapsAPILoaderConfigLiteral) {
const id = window.location.pathname.replace(/\//g, "");
return () => http.get<any>(`${environment.baseUrl}/map-display/${id}`).pipe(
map(response => {
config.apiKey = response.key;
return response;
})
).toPromise();
}
在我的情况下,必须向@NgModule中的providers数组添加一个指定函数的provider:
providers: [
{
provide: APP_INITIALIZER,
useFactory: agmConfigFactory,
deps: [HttpClient, LAZY_MAPS_API_CONFIG],
multi: true
}
],
对于我展示的一般示例,您可以使用Class而不是useFactory。
您仍然需要在@NgModule的imports数组中提供一个初始键,它可能是一个无意义的字符串
AgmCoreModule.forRoot({ apiKey: "initialKey"}),
AgmCoreModule.forRoot({ apiKey: "initialKey"}),