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

1

2 Answers 2

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

}
Sign up to request clarification or add additional context in comments.

5 Comments

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
In this case, I think these URLs are not going to change.
@Prashell, if your variables are public, you needn't use a function, just ExampleProvider.urlOne give you the value
I agree with the point @Eliseo, but what if I want to use them in the html file ?
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}}
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';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.