1

我正在尝试将带有 webpack2 项目的 angular2 转换为基于 angular-cli 的项目。

如果我理解正确的话,angular-cli 现在支持 webpack。在我原来的项目中,我注入了以下内容app.config.js

module.exports =  {
    webServer: {
        appBaseHref : JSON.stringify("/")
    },
    auth0: {
        apiKey: JSON.stringify("API_KEY"),
        domain: JSON.stringify("DOMAIN.auth0.com"),
        callbackUrl: JSON.stringify("CALLBACK_URL")
    }
};

通过将以下内容添加到webpack.config.js 文件中:

const appConfig = require("./config/app.config");
const DefinePlugin = require("webpack/lib/DefinePlugin");
...
module.exports = {
    plugins: [
       new DefinePlugin({
           APP_CONFIG: appConfig
       }),
...

然后在我的打字稿项目中,我会声明 APP_CONFIG ,declare var APP_CONFIG:any;然后我会使用它的属性。如何在 angular-cli 项目中注入这样的对象?

谢谢

4

1 回答 1

2

这是一个简单的示例,它仅使用带有setandget方法的普通服务:

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

@Injectable()

export class AppConfigService {

  public config: any = {
    apiKey: '[api_key]',
    domain: '[domain]',
    callbackUrl: '[callbackUrl]'
  }

  constructor() {}

  /* Allows you to update any of the values dynamically */
  set(k: string, v: any): void {
    this.config[k] = v;
  }

  /* Returns the entire config object or just one value if key is provided */
  get(k: string): any {
    return k ? this.config[k] : this.config;
  }
}

对于更复杂的用例,您可能希望将其转换为可观察的,但我认为在这个简单的情况下没有必要。

于 2016-10-14T06:24:21.490 回答