AndreFeijo AndreFeijo - 3 months ago 1052
TypeScript Question

Define global constants in Angular 2

In Angular 1.x you can define constants like this:

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


What would be the equivalent in Angular2 (with Typescript)?
I just don't want to repeat the API base url over and over again in all my services.

Answer

I resolved the problem by creating a class with static properties:

export class AppSettings {
   public static get API_ENDPOINT(): string { return 'http://127.0.0.1:6666/api/'; }
}

And then in the service:

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);
    }
}
Comments