1

I'm working in ionic3 app and I have a lot of services and functions using some special variables like:

let apiUrlPublic = 'http://localhost:8080/';

let apiUrl = 'http://localhost:9999/api/';

So I want to make those 2 variables global, like create one declaration and just call url by name.

Thanks in advance

Ragnar Lodbrok
  • 163
  • 1
  • 3
  • 16
  • 4
    Possible duplicate of [What is the best way to declare a global variable in Angular 2 / Typescript](https://stackoverflow.com/questions/36158848/what-is-the-best-way-to-declare-a-global-variable-in-angular-2-typescript) – bugs Apr 19 '18 at 12:24

2 Answers2

1

You can define a service in shared directory of you application. and wherever you want to use these values you can simply just inject that service in the constructor and access the variable.

import { Injectable } from '@angular/core';

@Injectable()
export class ExampleProvider {
  public urlOne: string = '....YOUR URL HERE....';
  public urlTwo = '....YOUR URL HERE....';

  constructor() {
  }
  getUrlOne() {
    return this.urlOne;
  }

 getUrlTwo() {
        return this.urlTwo;
      }

}
Prasheel
  • 985
  • 5
  • 22
  • This is right, however if you expect the global variable to change , then the best way is to make the global variable an Observable using the BehaviourSubject – Isaac Obella Apr 19 '18 at 12:48
  • In this case, I think these URLs are not going to change. – Prasheel Apr 19 '18 at 12:49
  • @Prashell, if your variables are public, you needn't use a function, just ExampleProvider.urlOne give you the value – Eliseo Apr 19 '18 at 16:22
  • I agree with the point @Eliseo, but what if I want to use them in the html file ? – Prasheel Apr 19 '18 at 16:29
  • if you want to use in a component, you can NOT use directly {{ExampleProvider.urlOne}}, you must add a getter in your component.ts: get urlOne(){return ExampleProvider.urlOne}, and put in your html {{urlOne}} – Eliseo Apr 19 '18 at 19:40
0

I got a simple solution, I create a new file:

globalVariables.ts

    export const GV = Object.freeze({
    sep: '/',
    version: '1.0',
    apiUrlPublic: 'http://localhost:8080/',
    apiUrl: 'http://localhost:9999/api/',
});

And when I want use any global variable I import file like that:

import { GV } from '../../app/globalVariables';

Ragnar Lodbrok
  • 163
  • 1
  • 3
  • 16