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

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

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

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


当前回答

如果你正在使用Webpack(我推荐使用Webpack),你可以为不同的环境设置常量。当每个环境都有不同的常数值时,这一点尤其有价值。

在你的/config目录下可能有多个webpack文件(例如,webpack.dev.js, webpack.prod.js等)。然后你会有一个custom- types .d。把t加在这里。下面是每个文件中要遵循的一般模式,以及组件中的示例用法。

网络包。{env}.js

const API_URL = process.env.API_URL = 'http://localhost:3000/';
const JWT_TOKEN_NAME = "id_token";
...
    plugins: [
      // NOTE: when adding more properties, make sure you include them in custom-typings.d.ts
      new DefinePlugin({
        'API_URL': JSON.stringify(API_URL),
        'JWT_TOKEN_NAME': JSON.stringify(JWT_TOKEN_NAME)
      }),

custom-typings.d.ts

declare var API_URL: string;
declare var JWT_TOKEN_NAME: string;
interface GlobalEnvironment {
  API_URL: string;
  JWT_TOKEN_NAME: string;
}

组件

export class HomeComponent implements OnInit {
  api_url:string = API_URL;
  authToken: string = "Bearer " + localStorage.getItem(JWT_TOKEN_NAME)});
}

其他回答

为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)
  }
 }

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

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

在阅读了这个帖子和其他一些帖子的所有答案后,我想提供我这些天正在使用的解决方案。

首先,我必须为环境添加一个类。这样,我就实现了属性的数据类型,因此使用起来很容易。此外,我还可以将默认数据绑定到我的环境,这样我就可以在所有环境之间共享公共数据。有时我们有一些在所有环境中具有相同值的变量(例如站点名称),并且我们不希望每次都更改到所有环境。

// environments\ienvironments.ts

export class IEnvironment implements IEnvironmentParams {
  public production: boolean;
  public basicURL: string = 'https://www.someawesomedomain.com';
  public siteName: string = 'My awesome site';

  constructor(params: IEnvironmentParams) {
    this.production = params.production ?? false;
    this.basicURL = params.basicURL ?? this.basicURL;
    this.siteName = params.siteName ?? this.siteName;
  }
}

export interface IEnvironmentParams {
  production: boolean;
  basicURL?: string;
  siteName?: string;
}

注意,我正在使用IEnvironmentParams来简化环境的创建,这样我就可以传递一个对象,而不会弄乱构造函数参数并避免参数顺序问题,还可以使用??操作符。

// environments\environment.prod.ts

import {IEnvironment, IEnvironmentParams} from "./ienvironment";

const params: IEnvironmentParams = {
    production: true
};

export const environment: IEnvironment = new IEnvironment(params);
// environments\environment.ts

import {IEnvironment, IEnvironmentParams} from "./ienvironment";

const params: IEnvironmentParams = {
    production: false
};

export const environment: IEnvironment = new IEnvironment(params);

用法示例

import {environment} from "../environments/environment";


// app-routing.module.ts

const routes: Routes = [
  { 
    path: '', component: HomeComponent,     
    data: {
        title: `${environment.siteName} | Home page title!`,
        description: 'some page description',
    }
  }
];

检查代码完成情况。

// home.component.ts

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent {

  constructor() {
    console.log(`home component constructor - showing evironment.siteName - ${environment.siteName}`);
  }
}

你可以在任何你想要的地方使用它,类、服务、指令、组件等等。

对于那些想知道在构建之后替换值的人。你能做到的。这有点棘手,但当你构建一个Angular应用时,环境数据会被导出到main.js中,看看下面的截图。

只需在任何IDE中打开文件并找到环境,然后只需替换数据。

关于Angular Universal项目。当Angular Universal项目构建完成时,它会导出两个main.js,一个用于服务器,一个用于浏览器,所以你必须同时修改两个。

如果你正在使用Webpack(我推荐使用Webpack),你可以为不同的环境设置常量。当每个环境都有不同的常数值时,这一点尤其有价值。

在你的/config目录下可能有多个webpack文件(例如,webpack.dev.js, webpack.prod.js等)。然后你会有一个custom- types .d。把t加在这里。下面是每个文件中要遵循的一般模式,以及组件中的示例用法。

网络包。{env}.js

const API_URL = process.env.API_URL = 'http://localhost:3000/';
const JWT_TOKEN_NAME = "id_token";
...
    plugins: [
      // NOTE: when adding more properties, make sure you include them in custom-typings.d.ts
      new DefinePlugin({
        'API_URL': JSON.stringify(API_URL),
        'JWT_TOKEN_NAME': JSON.stringify(JWT_TOKEN_NAME)
      }),

custom-typings.d.ts

declare var API_URL: string;
declare var JWT_TOKEN_NAME: string;
interface GlobalEnvironment {
  API_URL: string;
  JWT_TOKEN_NAME: string;
}

组件

export class HomeComponent implements OnInit {
  api_url:string = API_URL;
  authToken: string = "Bearer " + localStorage.getItem(JWT_TOKEN_NAME)});
}

我有另一种定义全局常数的方法。因为如果我们在ts文件中定义,如果在生产模式中构建,就不容易找到常数来改变值。

export class SettingService  {

  constructor(private http: HttpClient) {

  }

  public getJSON(file): Observable<any> {
      return this.http.get("./assets/configs/" + file + ".json");
  }
  public getSetting(){
      // use setting here
  }
}

在app文件夹中,我添加文件夹configs/setting.json

设置.json中的内容

{
    "baseUrl": "http://localhost:52555"
}

在app模块中添加APP_INITIALIZER

   {
      provide: APP_INITIALIZER,
      useFactory: (setting: SettingService) => function() {return setting.getSetting()},
      deps: [SettingService],
      multi: true
    }

通过这种方式,我可以更容易地更改json文件中的值。 我还将这种方法用于常量错误/警告消息。