5

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?

CRCameron
  • 53
  • 4
  • 2
    What's the error message you're getting if the variable doesn't exist? In any case, I think you should rather use the `typeof` operator to check for existence, see https://stackoverflow.com/questions/5113374/javascript-check-if-variable-exists-is-defined-initialized . – balu Oct 25 '17 at 10:25

1 Answers1

1

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;
    }
}
Mugurel
  • 198
  • 10