在Angular 7中动态更改agm-map google maps API密钥

我正在构建一个应用程序,可让您编辑地图,编辑器具有带有Agm地图模块的google地图,最终结果是用户将iframe与他的地图嵌入到自己的网页中。 我将模块用于编辑器,并在app.module.ts中使用API​​密钥导入该模块。

import { AgmCoreModule } from '@agm/core';
...
imports: [
 ...
 AgmCoreModule.forRoot({
   apiKey: 'YOUR_KEY'
 })
]

iframe将是使用相同后端的单独的角度应用程序。我需要将从数据库中获取的用户的API密钥,但是我无法理解如何在Angular中构建此部分,似乎它可以使用api密钥创建构建,是否有可能做到这一点以某种方式在运行时修改密钥?我已经在jQuery中看到了。可以从script标记或普通js中的代码中获取代码的地方,例如:

<script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>

在最后一个示例中,可以轻松完成此操作, 谢谢

iCMS 回答:在Angular 7中动态更改agm-map google maps API密钥

我确实立即解决了这个问题,就我而言,我从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();
}

api调用的内容和id可以用所需的键替换。

import { AgmCoreModule,LazyMapsAPILoaderConfigLiteral } 
from '@agm/core';

@Injectable()
export class GoogleMapsConfig implements LazyMapsAPILoaderConfigLiteral {
  apiKey: string = CONFIG.googleMapsAPIKey;
}


在我的情况下,您必须在@NgModule中的providers数组中添加一个指定函数的提供程序:

  providers: [
    {
        provide: APP_INITIALIZER,useFactory: agmConfigFactory,deps: [HttpClient,LAZY_MAPS_API_CONFIG],multi: true
    } 
  ],

对于我显示的一般示例,您可以使用Class而不是useFactory。 您仍然必须在@NgModule的imports数组中提供一个初始键,它可以是无意义的字符串

    AgmCoreModule.forRoot({ apiKey: "initialKey"}),
本文链接:https://www.f2er.com/2225113.html

大家都在问