在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。
当前回答
只需使用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/'}), ...]);
其他回答
所有的解决方案似乎都很复杂。我在寻找这种情况下最简单的解我只想用常数。常量很简单。是否有反对以下解决方案的意见?
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 2中创建应用范围常量的最佳方法是使用environment。ts文件。声明这些常量的好处是,您可以根据环境改变它们,因为每个环境可以有不同的环境文件。
我有另一种定义全局常数的方法。因为如果我们在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文件中的值。 我还将这种方法用于常量错误/警告消息。
只需使用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/'}), ...]);
在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);