Angular noob - how to set a global variable?


#1

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('app.services', [])

.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();
            $http.post(api_url+'post/user/login?username='+data.username+'&password='+data.password).then(function(resp){
                console.log(resp);
                if (resp.data.status == 'ok') {
                    deferred.resolve(resp.data);
                    SessID = resp.data.session_id;
                    //console.log(SessID);
                } else {
                    deferred.reject('Wrong credentials.');
                }
            });
            return deferred.promise;
        },
        
        isAuthenticated: function(){
            //console.log(SessID);
            if (SessID !== null) {
                return true;
            } else {
                return false;
            }
        },
        
        logoutUser: function(){
            var deferred = $q.defer();
            $http.get(api_url+'get/user/logout?session_id='+SessID).then(function(resp){
                console.log(resp);
                SessID = null;
                //console.log(SessID);
                deferred.resolve(resp.data);
            });
            return deferred.promise;
        },
    }
    return ret;

}]);

#2

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


#3

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


#4

Hall of Heroes tutorial.


#5

See:


#6

Hi.
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 https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class GlobalProvider {
//this is a global variable
  public url = "http://172.16.137.17/";

  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';
@Component({
  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.


#7

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


#8

oh, you are right jajajaja


#9

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.