在Angular 1.x中,您可以像这样定义常量:
angular.module('mainApp.config', [])
.constant('API_ENDPOINT', 'http://127.0.0.1:6666/api/')
在Angular (使用TypeScript)中的等价物是什么?
我只是不想在我的所有服务中一遍又一遍地重复API基础url。
发布于 2016-10-27 22:19:29
angular团队自己提供的配置解决方案可以在here中找到。
以下是所有相关代码:
1) app.config.ts
import { OpaqueToken } from "@angular/core";
export let APP_CONFIG = new OpaqueToken("app.config");
export interface IAppConfig {
apiEndpoint: string;
}
export const AppConfig: IAppConfig = {
apiEndpoint: "http://localhost:15422/api/"
};
2) app.module.ts
import { APP_CONFIG, AppConfig } from './app.config';
@NgModule({
providers: [
{ provide: APP_CONFIG, useValue: AppConfig }
]
})
3) your.service.ts
import { APP_CONFIG, IAppConfig } from './app.config';
@Injectable()
export class YourService {
constructor(@Inject(APP_CONFIG) private config: IAppConfig) {
// You can use config.apiEndpoint now
}
}
现在,您可以在任何地方注入配置,而无需使用字符串名称,只需使用接口进行静态检查即可。
当然,您可以进一步分离接口和常量,以便能够在生产和开发中提供不同的值。
发布于 2017-07-28 22:17:48
在Angular 4中,你可以使用环境类来保存所有的全局变量。
默认情况下,您有environment.ts和environment.prod.ts。
例如
export const environment = {
production: false,
apiUrl: 'http://localhost:8000/api/'
};
然后在你的服务下
import { environment } from '../../environments/environment';
...
environment.apiUrl;
发布于 2016-01-25 15:12:01
只需使用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/'}), ...]);
https://stackoverflow.com/questions/34986922
复制相似问题