【问题标题】:Typescript - Declare optional global variable打字稿 - 声明可选的全局变量
【发布时间】:2022-03-19 01:03:48
【问题描述】:

我正在创建一个服务来检查用户是否已登录。这将只是一个从后端传递的全局变量“userIsLoggedIn”。此服务将在多个应用程序中使用,有时 userIsLoggedIn 全局变量将不存在。

我所拥有的是……

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

declare const userIsLoggedIn: boolean;

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

如果 userIsLoggedIn 全局变量不存在,则会出现错误,如果省略声明行,则会出现错误。

我曾希望能够做类似的事情

declare const userIsLoggedIn?: boolean;

但这似乎不起作用。有人可以帮帮我吗?

【问题讨论】:

标签: angular typescript angular2-services


【解决方案1】:

如果我检查了(typeof userIsLoggedIn !== 'undefined'),它会起作用。我尝试过的其他任何方法都没有奏效。您的代码现在应该如下所示:

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

declare let userIsLoggedIn: boolean;

@Injectable()
export class UserLoggedInService{
    isUserLoggedIn(): boolean {
        if(typeof userIsLoggedIn !== 'undefined'){
            return userIsLoggedIn;
        }

        return false;
    }
}

【讨论】:

    猜你喜欢
    • 2017-10-22
    • 2021-02-17
    • 1970-01-01
    • 2016-03-27
    • 2012-11-28
    • 1970-01-01
    • 2017-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多