【问题标题】:How to define a variable in external config file and use it in app.module如何在外部配置文件中定义一个变量并在 app.module 中使用它
【发布时间】:2018-05-23 20:53:27
【问题描述】:

在带有 Angular 5 的 Ionic 3 中,我试图在 app.config.ts 文件中定义所有外部 API 密钥。

我必须声明一个类,否则我会收到 ngc 引发的 AOT 错误。

这是我的 app.config.ts

import { Injectable } from '@angular/core';

@Injectable()
export class AppConfig {
  public ONESIGNAL_API_KEY: string;
  public FIREBASE_CONFIG: any;
  public MIXPANEL_TOKEN: string;

  constructor() {
    this.ONESIGNAL_API_KEY = 'myoskey';
    this.FIREBASE_CONFIG = {
      apiKey: "myfbkey",
      authDomain: "myfbdomain
      };
    this.MIXPANEL_TOKEN = 'mymptoken';
  }
}

我可以将它注入到其他类的构造函数中,但 firebase 必须在 app.module.ts 中初始化。所以我尝试执行以下操作 // 配置

import {AppConfig} from './app-config';
...
imports: [
    BrowserModule,
    HttpClientModule,
    IonicModule.forRoot(MyApp, {
      backButtonText: '',
      tabsHideOnSubPages: true,
      //scrollAssist: true,
      //autoFocusAssist: true
    }),
    IonicStorageModule.forRoot(),
    IonicImageLoader.forRoot(),
    AngularFireModule.initializeApp(AppConfig.FIREBASE_CONFIG),
    ....

不幸的是,我收到以下错误 Property 'FIREBASE_CONFIG' does not exist on type 'typeof AppConfig'.

如何在这个app.config文件中声明FIREBASE_CONFIG并直接在app.module中使用?

我尝试像这样在构造函数之前直接初始化变量,但结果相同

import { Injectable } from '@angular/core';

@Injectable()
export class AppConfig {
  public ONESIGNAL_API_KEY: string;
  public FIREBASE_CONFIG: any = {
      apiKey: "myfbkey",
      authDomain: "myfbdomain
      };
  public MIXPANEL_TOKEN: string;

  constructor() {
    this.ONESIGNAL_API_KEY = 'myoskey';
    this.MIXPANEL_TOKEN = 'mymptoken';
  }
}

有什么想法吗?

【问题讨论】:

    标签: angular typescript ionic3 angular5 angular-aot


    【解决方案1】:

    你可以使用枚举:

    export enum AppConfig {
        ONESIGNAL_API_KEY = 'myoskey',
        MIXPANEL_TOKEN = 'mymptoken'
    }
    
    export const FIREBASE_CONFIG = {
        apiKey : "myfbkey",
        authDomain : "myfbdomain"
    }
    

    然后你照常使用它:

    import {AppConfig ,FIREBASE_CONFIG  } from './config';
    ...
    imports: [
        //...
        AngularFireModule.initializeApp(FIREBASE_CONFIG)
    

    注意:您收到该错误是因为您尝试访问 AppConfig.FIREBASE_CONFIG 并且 FIREBASE_CONFIGAppConfig 类的非静态属性。

    【讨论】:

    • 我收到以下关于 FIREBASE_CONFIG 的错误:Computed values are not permitted in an enum with string valued members.
    • 只要我使用除类以外的其他东西,我就会收到以下错误(我认为是 Angular 5):Error encountered resolving symbol values statically. Could not resolve ./app-config.ts relative to /Users/me/myproj/src/app/app.module.ts., resolving symbol AppModule in /Users/me/myproj/src/app/app.module.ts, resolving symbol AppModule in /Users/me/myproj/src/app/app.module.ts, resolving symbol AppModule in /Users/me/myproj/src/app/app.module.ts Error: The Angular AoT build failed.
    猜你喜欢
    • 2015-08-04
    • 1970-01-01
    • 1970-01-01
    • 2018-08-04
    • 1970-01-01
    • 2013-01-04
    • 1970-01-01
    • 1970-01-01
    • 2013-05-18
    相关资源
    最近更新 更多