在Angular 1中。X你可以这样定义常量:

angular.module('mainApp.config', [])
    .constant('API_ENDPOINT', 'http://127.0.0.1:6666/api/')

在Angular中(使用TypeScript)会是什么?

我只是不想在我的所有服务中一遍又一遍地重复API基url。


当前回答

以下是我最近在这种情况下的经验:

@angular / cli: 1.0.0 节点:6.10.2 @angular /核心:4.0.0

我在这里遵循了官方和更新的文档:

https://angular.io/docs/ts/latest/guide/dependency-injection.html !# dependency-injection-tokens

似乎OpaqueToken现在已弃用,我们必须使用InjectionToken,所以这些是我的文件运行起来像一个魅力:

app-config.interface.ts

export interface IAppConfig {

  STORE_KEY: string;

}

app-config.constants.ts

import { InjectionToken } from "@angular/core";
import { IAppConfig } from "./app-config.interface";

export const APP_DI_CONFIG: IAppConfig = {

  STORE_KEY: 'l@_list@'

};

export let APP_CONFIG = new InjectionToken< IAppConfig >( 'app.config' );

app.module.ts

import { APP_CONFIG, APP_DI_CONFIG } from "./app-config/app-config.constants";

@NgModule( {
  declarations: [ ... ],
  imports: [ ... ],
  providers: [
    ...,
    {
      provide: APP_CONFIG,
      useValue: APP_DI_CONFIG
    }
  ],
  bootstrap: [ ... ]
} )
export class AppModule {}

my-service.service.ts

  constructor( ...,
               @Inject( APP_CONFIG ) private config: IAppConfig) {

    console.log("This is the App's Key: ", this.config.STORE_KEY);
    //> This is the App's Key:  l@_list@

  }

结果是干净的,主机上没有任何警告,这要感谢John Papa最近在这个问题上的评论:

https://github.com/angular/angular-cli/issues/2034

该键在接口的另一个文件中实现。

其他回答

在Angular 4中,你可以使用环境类来保存所有的全局变量。

你有环境。Ts和environment. products . Ts。

例如

export const environment = {
  production: false,
  apiUrl: 'http://localhost:8000/api/'
};

在你的服务中:

import { environment } from '../../environments/environment';
...
environment.apiUrl;

只需使用Typescript常量

export var API_ENDPOINT = 'http://127.0.0.1:6666/api/';

你可以在依赖注入器中使用

bootstrap(AppComponent, [provide(API_ENDPOINT, {useValue: 'http://127.0.0.1:6666/api/'}), ...]);

使用构建过程中生成的属性文件非常简单。这就是Angular CLI使用的方法。为每个环境定义一个属性文件,并在构建期间使用命令来确定将哪个文件复制到应用程序中。然后简单地导入属性文件来使用。

https://github.com/angular/angular-cli#build-targets-and-environment-files

所有的解决方案似乎都很复杂。我在寻找这种情况下最简单的解我只想用常数。常量很简单。是否有反对以下解决方案的意见?

app.const.ts

'use strict';

export const dist = '../path/to/dist/';

app.service.ts

import * as AppConst from '../app.const'; 

@Injectable()
export class AppService {

    constructor (
    ) {
        console.log('dist path', AppConst.dist );
    }

}

为Angular 4+更新

现在,如果你的项目是通过angular-cli生成的,我们可以简单地使用angular提供的默认环境文件。

例如

在环境文件夹中创建以下文件

environment.prod.ts environment.qa.ts environment.dev.ts

每个文件都可以保存相关的代码更改,例如:

environment.prod.ts export const environment = { production: true, apiHost: 'https://api.somedomain.com/prod/v1/', CONSUMER_KEY: 'someReallyStupidTextWhichWeHumansCantRead', codes: [ 'AB', 'AC', 'XYZ' ], }; environment.qa.ts export const environment = { production: false, apiHost: 'https://api.somedomain.com/qa/v1/', CONSUMER_KEY : 'someReallyStupidTextWhichWeHumansCantRead', codes: [ 'AB', 'AC', 'XYZ' ], }; environment.dev.ts export const environment = { production: false, apiHost: 'https://api.somedomain.com/dev/v1/', CONSUMER_KEY : 'someReallyStupidTextWhichWeHumansCantRead', codes: [ 'AB', 'AC', 'XYZ' ], };

应用程序中的用例

您可以将环境导入到任何文件中,例如服务clientUtilServices.ts

从'../../environments/environment'导入{environment};

getHostURL(): string {
    return environment.apiHost;
  }

构建中的用例

打开你的angular cli文件。angular-cli。Json和“apps”内部:[{…}]添加以下代码

 "apps":[{
        "environments": {
            "dev": "environments/environment.ts",
            "prod": "environments/environment.prod.ts",
            "qa": "environments/environment.qa.ts",
           }
         }
       ]

如果你想在生产环境中构建,运行ng build——env=prod,它会从environment. product .ts中读取配置,就像你在qa或dev中做的一样

##老答案

我一直在做的事情如下,在我的提供者:

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

@Injectable()
export class ConstantService {

API_ENDPOINT :String;
CONSUMER_KEY : String;

constructor() {
    this.API_ENDPOINT = 'https://api.somedomain.com/v1/';
    this.CONSUMER_KEY = 'someReallyStupidTextWhichWeHumansCantRead'
  }
}

然后我可以在任何地方访问所有常量数据

import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';

import {ConstantService} from  './constant-service'; //This is my Constant Service


@Injectable()
export class ImagesService {
    constructor(public http: Http, public ConstantService: ConstantService) {
    console.log('Hello ImagesService Provider');

    }

callSomeService() {

    console.log("API_ENDPOINT: ",this.ConstantService.API_ENDPOINT);
    console.log("CONSUMER_KEY: ",this.ConstantService.CONSUMER_KEY);
    var url = this.ConstantService.API_ENDPOINT;
    return this.http.get(url)
  }
 }