Angular noob - how to set a global variable?

I have set up an angular module to allow me to login(), checkloggedin(), and logout() function. The problem is, the retrieved variable ‘SessID’ is currently only accessible from within this angular module. Since I need to pass the the session id with every $http request throughout the app, I need this variable to be accessible wherever I need it. Is there a way to make this variable “global” (is that even the right terminology for angular?). Any help appreciated. Thank you!

angular.module('', [])

.service('LoginCtrl', ['$http', '$q', function($http, $q){

    var api_url = 'https://xxxxx/api/';
    var SessID = null;

    var ret = {
        loginUser: function(data){
            var deferred = $q.defer();
                if ( == 'ok') {
                    SessID =;
                } else {
                    deferred.reject('Wrong credentials.');
            return deferred.promise;
        isAuthenticated: function(){
            if (SessID !== null) {
                return true;
            } else {
                return false;
        logoutUser: function(){
            var deferred = $q.defer();
                SessID = null;
            return deferred.promise;
    return ret;


Don’t create global variables. If you need to store global state in Angular, use a provider.

Thank you! Could you demonstrate how I can do that or point me to a demo?

Hall of Heroes tutorial.


You can do something like this:

ionic g provider global

that generate this:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

  Generated class for the GlobalProvider provider.

  See for more info on providers
  and Angular DI.
export class GlobalProvider {
//this is a global variable
  public url = "";

  constructor(public http: HttpClient) {
    console.log('Hello GlobalProvider Provider');


and in your other .ts you can call the provider like this:

import { GlobalProvider } from '../../providers/global/global';
  selector: 'page-home',
  templateUrl: 'home.html'
export class HomePage {
  urlGet = "residencia/webservices/view-home.php";

  constructor(public navCtrl: NavController, public menuCtrl: MenuController, public app: App,
  public http: HttpClient, public global: GlobalProvider, public platform: Platform) {
    this.menuCtrl.enable(true, 'myMenu');
//here call the global variable and concat with other
    this.urlGet = global.url + this.urlGet;

I hope this can help you.

Am I the only one who thinks OP is trying to do this in v1?

oh, you are right jajajaja

Yes, I apologize. I am using Ionic 1.3.2 within the Ionic Creator online builder. @Nyxot thank you! I will check this out today after work–will it work in v1? I am not sure Creator gives me access to edit all of these files.