2

我正在构建一个允许您编辑地图的应用程序,编辑器具有带有 Agm 地图模块的谷歌地图,用户的最终结果是一个 iframe,其地图嵌入到他的网页中。我正在为编辑器使用该模块,并在 app.module.ts 中使用我的 API 密钥导入它。

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

iframe 将是一个使用相同后端的独立 Angular 应用程序。我需要将从数据库中获取的用户的 API 密钥,但我不知道如何在 Angular 中构建这部分,似乎它使用 api 密钥创建构建,是否可以这样做以某种方式在运行时修改密钥?我已经看到它是在 jQuery 中完成的。可以从 script 标签或 vanilla js 中的代码中获取它,例如:

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

在最后一个例子中,它可以很容易地完成,谢谢

4

2 回答 2

2

我确实立即解决了它,在我的情况下,我使用此代码从 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, LAZY_MAPS_API_CONFIG, LazyMapsAPILoaderConfigLiteral } 
from '@agm/core';

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


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

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

对于我展示的通用示例,您可以使用 useClass 而不是 useFactory。你仍然需要在 @NgModule 的 imports 数组中提供一个初始键,它可以是一个无意义的字符串

    AgmCoreModule.forRoot({ apiKey: "initialKey"}),

于 2020-07-30T11:14:41.607 回答
0

添加到上面的答案,添加以下内容以使自动完成工作

AgmCoreModule.forRoot({
  apiKey: 'initialKey',
  language: 'en',
  libraries: ['places']
}),
于 2022-03-05T17:27:38.453 回答