从 config.json 文件中提供 google 映射 api 键

provide google maps api key from config.json file

我有 config.json 文件,我已经在其中设置了所有网址和密钥。有一个名为 "googleMapsApiKey" 的参数,其中我有我的 "map key"。我想将此密钥提供给我的模块文件,以便我可以使用 google 映射,但我无法提供它。下面是我的代码。

config.json

{
      "googleMapsApiKey": "MY KEY",
   }

MobileContentModule.ts

import { ConfigService } from '../../../HiP-CmsAngularApp/app/config.service';

    @NgModule({
      imports: [
        AgmCoreModule.forRoot({
          apiKey: 'WANT TO PROVIDE THAT KEY HERE', ---> from config.json
          libraries: ['places']
        }),
        CommonModule,
        FormsModule,

有一项名为 ConfigService 的服务可供我访问我的 config.json 文件。我已将此服务导入 MobileContentModule.ts 文件。

谁能帮我从 config.json 文件中获取 google api 密钥?这样做的目的是,我们不想在 github.

上公开此密钥

像这样将其导入到您的文件中:

import data from './config.json';
[...]
AgmCoreModule.forRoot({
  apiKey: data.googleMapsApiKey
  libraries: ['places']
}),[...]

但是TypeScript 2+会抱怨Cannot find module 'config.json'。 然后你必须使用像

这样的通配符声明
declare module "json!*" {
    const value: any;
    export default value;
}

(参见 https://www.typescriptlang.org/docs/handbook/modules.html#wildcard-module-declarations

在 Angular 6.1+:

app.module.ts

import * as fromConfig from 'config.json';

@NgModule({
imports: [
AgmCoreModule.forRoot({
            apiKey: fromConfig.googleJSAPIKey,
            libraries: ['places'],
        }),]
})

tsconfig.json:

{
    "compilerOptions": {
        "resolveJsonModule": true,
        "esModuleInterop": true
    }
}