Search code examples
angulartypescriptimport

importing a variable from one typescript file into another


I am attempting to import a variable from one type script file into another.

the variable I want to import is cityListUrl

the type script file it is in is coded like this:

export class backendUrls{

  // root url
  rooturl:string= 'http://127.0.0.1:8000';

//get a list of all cities
  cityListUrl:string = this.rooturl + '/api/city/';


}

the file I want to import it into looks like this:

import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import {backendUrls} from 'app/backendUrls';

@Injectable()
export class cityGetService{
  constructor(private http: Http){}

  cityGet(){
    this.http.get(backendUrls.cityListUrl)
  }
}

the cityListUrl in my pycharm editor is currently red. with the message

TS2339: 'cityListUrl' does not exist on type 'typeof backendUrls'.

has anyone had this issue before? How would I fix this? Thank you


Solution

  • The best way to handle server api urls is to use the angular environment files. There are two main advantages of its usage:

    • It's available in all your application
    • You can handle multiples platform (localhost, dev, stating, prod) without modifing your code

    in app/environments you can create differents files, like:

    • environments.prod.ts
    • environments.ts
    • environement.test.ts

    In each file you define your global variables:

    For localhost change your code into:

    export const environment = {
      production: false,
      apiHost: 'http://localhost',
      recaptchaKey: '6LeWzxQUeazeAAPpR0gZFezaeazL5AvUP3moN1U4u',
      fileHost: 'http://file.localhost',
    };
    

    For prod example, do instead:

    export const environment = {
      production: true,
      apiHost: 'http://prod',
      recaptchaKey: '6LeWzxQUeazeAAPpR0gZFezaeazL5AvUP3moN1U4u',
      fileHost: 'http://file.prod',
    };
    

    To use it in your scripts you only need to import:

    import { environment } from './environments/environment' //relative path from where your file is
    export class Service {
        protected cityListUrl = '/api/city/';
    
        constructor(protected http: Http) { }
    
        get() {
          this.http.get(environment.apiHost + this.cityListUrl).map(response => response.json());
        }
    }
    

    When you build your project with angular-cli, you have to specify which environment you want to use. For example, you can execute either

    ng build --environment=prod

    or

    ng serve --environment=test

    Which it is cool because you can easily integrate this command line in a continuous integration tool.