AndreFeijo AndreFeijo - 1 year ago 4123
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', '')

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 Source

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

export class AppSettings {
   public static get API_ENDPOINT(): string { return ''; }

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';

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 => this.parseData(message));

    private parseData(data): Message {
        return new Message(data);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download