在Angular 1中。X你可以这样定义常量:
angular.module('mainApp.config', [])
.constant('API_ENDPOINT', 'http://127.0.0.1:6666/api/')
在Angular中(使用TypeScript)会是什么?
我只是不想在我的所有服务中一遍又一遍地重复API基url。
在Angular 1中。X你可以这样定义常量:
angular.module('mainApp.config', [])
.constant('API_ENDPOINT', 'http://127.0.0.1:6666/api/')
在Angular中(使用TypeScript)会是什么?
我只是不想在我的所有服务中一遍又一遍地重复API基url。
当前回答
虽然有一个AppSettings类和一个字符串常量作为ApiEndpoint的方法是可行的,但这并不理想,因为我们不能在单元测试时将这个真正的ApiEndpoint交换为其他一些值。
我们需要能够将这个api端点注入到我们的服务中(想象一下将一个服务注入到另一个服务中)。我们也不需要为此创建一个完整的类,我们所要做的只是将一个字符串注入到我们的服务中,作为我们的ApiEndpoint。为了完成这个完美的答案,下面是在Angular 2中如何完成的完整代码:
首先,我们需要告诉Angular,当我们在应用中请求ApiEndpoint时,如何提供它的实例(把它看作是注册一个依赖):
bootstrap(AppComponent, [
HTTP_PROVIDERS,
provide('ApiEndpoint', {useValue: 'http://127.0.0.1:6666/api/'})
]);
然后在服务中,我们将这个ApiEndpoint注入到服务的构造函数中,Angular会根据我们上面的注册为我们提供它:
import {Http} from 'angular2/http';
import {Message} from '../models/message';
import {Injectable, Inject} from 'angular2/core'; // * We import Inject here
import {Observable} from 'rxjs/Observable';
import {AppSettings} from '../appSettings';
import 'rxjs/add/operator/map';
@Injectable()
export class MessageService {
constructor(private http: Http,
@Inject('ApiEndpoint') private apiEndpoint: string) { }
getMessages(): Observable<Message[]> {
return this.http.get(`${this.apiEndpoint}/messages`)
.map(response => response.json())
.map((messages: Object[]) => {
return messages.map(message => this.parseData(message));
});
}
// the rest of the code...
}
其他回答
只需使用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/'}), ...]);
如果你正在使用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)});
}
你可以为你的全局变量创建一个类,然后像这样导出这个类:
export class CONSTANT {
public static message2 = [
{ "NAME_REQUIRED": "Name is required" }
]
public static message = {
"NAME_REQUIRED": "Name is required",
}
}
在创建并导出你的CONSTANT类之后,你应该在你想要使用的类中导入这个类,就像这样:
import { Component, OnInit } from '@angular/core';
import { CONSTANT } from '../../constants/dash-constant';
@Component({
selector : 'team-component',
templateUrl: `../app/modules/dashboard/dashComponents/teamComponents/team.component.html`,
})
export class TeamComponent implements OnInit {
constructor() {
console.log(CONSTANT.message2[0].NAME_REQUIRED);
console.log(CONSTANT.message.NAME_REQUIRED);
}
ngOnInit() {
console.log("oninit");
console.log(CONSTANT.message2[0].NAME_REQUIRED);
console.log(CONSTANT.message.NAME_REQUIRED);
}
}
你可以在构造函数或ngOnInit(){}或任何预定义方法中使用它。
为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)
}
}
所有的解决方案似乎都很复杂。我在寻找这种情况下最简单的解我只想用常数。常量很简单。是否有反对以下解决方案的意见?
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 );
}
}