[英]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.我正在创建一个服务来检查用户是否登录。这只是一个从后端传递的全局变量“userIsLoggedIn”。 This service will be used across several applications and sometimes the userIsLoggedIn global variable will not exist.
此服务将跨多个应用程序使用,有时 userIsLoggedIn 全局变量将不存在。
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.如果 userIsLoggedIn 全局变量不存在,那么我会得到一个错误,如果我遗漏了声明行,那么我会得到一个错误。
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?
有人可以帮我吗?
Form me it worked if I made the check (typeof userIsLoggedIn !== 'undefined')
.如果我进行检查
(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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.