Define constant in angular 2


Say you are fetching JSON data from an api url which is http://localhost:8080/api, and you have to use it for a a number of times

You can declare the variable as

export var API_ENDPOINT = 'http://localhost:8080/api';

and later you can call this variable as

return this._http.get(API_ENDPOINT+'/getLoggedUser')

Complete code example

import {Injectable} from 'angular2/core';
import {Http,Response,Headers} from 'angular2/http';
import 'rxjs/add/operator/map';
import {Observable} from 'rxjs/Observable';
import 'rxjs/Rx';
export var API_ENDPOINT = 'http://localhost:8080/api';

@Injectable()

export class AppService{

  constructor(private _http:Http){}
  getUsers(){
      console.log("user info fetching");
      return this._http.get(API_ENDPOINT+'/getLoggedUser')
      .map((res:Response)=>res.json());
  }
}

Leave a Reply