定义全局常量

13 浏览
0 Comments

定义全局常量

在 Angular 1.x 中,您可以像这样定义常量:

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

在 Angular 中(使用 TypeScript),相当于什么呢?

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

admin 更改状态以发布 2023年5月23日
0
0 Comments

解决方案可以在angular团队提供的配置文档中找到此处.

下面是相关的代码:

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

现在,您可以在任何地方注入配置而不使用字符串名称,并使用您的接口进行静态检查。

当然,您可以进一步分离接口和常量,以便在生产和开发中提供不同的值,例如:

0
0 Comments

以下更改适用于我的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 {
        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);
    }
}

0