Search code examples
angulartypescriptangular2-services

Typescript - Declare optional global variable


I am creating a service to check if a user is logged in. This will just be a global variable 'userIsLoggedIn' which is passed from the backend. This service will be used across several applications and sometimes the userIsLoggedIn global variable will not exist.

What I have is...

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

declare const userIsLoggedIn: boolean;

@Injectable()
export class UserLoggedInService{
    isUserLoggedIn(): boolean {
        return userIsLoggedIn || false;
    }
}

If the userIsLoggedIn global variable does not exist then I get an error and if I leave out the declaration line then I get an error.

I had hoped to be able to do something like

declare const userIsLoggedIn?: boolean;

But this does not seem to work. Could anybody help me out please?


Solution

  • Form me it worked if I made the check (typeof userIsLoggedIn !== 'undefined') . Anything else that I have tried didn't worked. Your code now should look like this:

    import { Injectable } from '@angular/core';
    
    declare let userIsLoggedIn: boolean;
    
    @Injectable()
    export class UserLoggedInService{
        isUserLoggedIn(): boolean {
            if(typeof userIsLoggedIn !== 'undefined'){
                return userIsLoggedIn;
            }
    
            return false;
        }
    }