在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 2最终版上是有效的:

export class AppSettings {
   public static API_ENDPOINT='http://127.0.0.1:6666/api/';
}

然后在服务中:

import {Http} from 'angular2/http';
import {Message} from '../models/message';
import {Injectable} from 'angular2/core';
import {Observable} from 'rxjs/Observable';
import {AppSettings} from '../appSettings';
import 'rxjs/add/operator/map';

@Injectable()
export class MessageService {

    constructor(private http: Http) { }

    getMessages(): Observable<Message[]> {
        return this.http.get(AppSettings.API_ENDPOINT+'/messages')
            .map(response => response.json())
            .map((messages: Object[]) => {
                return messages.map(message => this.parseData(message));
            });
    }

    private parseData(data): Message {
        return new Message(data);
    }
}

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

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

例如

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

在你的服务中:

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

在Angular2中,你有以下提供定义,它允许你设置不同类型的依赖:

provide(token: any, {useClass, useValue, useExisting, useFactory, deps, multi}

与Angular 1的比较

在Angular1中,app.service等价于Angular2中的useClass。

Angular1中的app.factory相当于Angular2中的useFactory。

app.constant和app.value被简化为useValue,约束更少。也就是说,不再有配置块了。

app.provider——在Angular 2中没有等价的。

例子

使用根注入器进行设置:

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

或者使用组件的注入器进行设置:

providers: [provide(API_ENDPOINT, { useValue: 'http://127.0.0.1:6666/api/'})]

提供是对…的简称:

var injectorValue = Injector.resolveAndCreate([
  new Provider(API_ENDPOINT, { useValue: 'http://127.0.0.1:6666/api/'})
]);

使用注入器,获取值很容易:

var endpoint = injectorValue.get(API_ENDPOINT);

如果你正在使用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)});
}

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

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

// 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,一个用于服务器,一个用于浏览器,所以你必须同时修改两个。