【问题标题】:what is the alternative for the util.isNullOrUndefined(object) in the Util module ? Angular 7Util 模块中 util.isNullOrUndefined(object) 的替代方法是什么?角 7
【发布时间】:2023-03-05 14:21:01
【问题描述】:

util.isNullOrUndefined(object) 已被贬值,我找不到任何替代品。有人可以指出一个可行的替代方案吗?

if (isNullOrUndefined(this.activeAppKey) || this.activeAppKey.trim().length === 0) {
  this.activeAppKey = sessionStorage.getItem(AppConstants.APP_KEY);
}

【问题讨论】:

  • if (!this.activeAppKey || this.activeAppKey.trim().length === 0) { this.activeAppKey = sessionStorage.getItem(AppConstants.APP_KEY); }

标签: angular module


【解决方案1】:

尝试使用! 运算符。

if (!this.activeAppKey) {
  this.activeAppKey = sessionStorage.getItem(AppConstants.APP_KEY);
}

【讨论】:

  • 使用! 操作符可能会导致一些麻烦,当变量为数字0、空字符串等时。请参阅此答案:stackoverflow.com/questions/28975896/…
  • 它会为类似 ` if (!isNullOrUndefined(user.customRoles[this.activeAppKey])) { ui.role = user.customRoles[this.activeAppKey].roleKey; }`
  • 你检查过用户本身是空的吗?
  • 解释Javascript truthy可能是个好主意。
  • 您不能使用! 运算符。因为如果 this.activeAppKey 值的条件主体是 false 而不是 nullundefined,这将不允许您输入。
【解决方案2】:

为什么不简单地创建你自己的:

export function isNullOrUndefined(value: any) {
    return value === null || value === undefined;
}

假设您创建一个 tools.ts 文件并编写上述代码:

您可以按如下方式在组件中使用它:

import { isNullOrUndefined } from 'tools';

上面的代码在那里没有任何变化。另外它可以重复使用

【讨论】:

    【解决方案3】:

    从“是什么”导入它

    所以,

    import { isUndefined, isNullOrUndefined } from 'util';

    会变成,

    import { isUndefined, isNullOrUndefined } from 'is-what';

    【讨论】:

      【解决方案4】:

      试试这个:

      if (this.activeAppKey === null || this.activeAppKey === undefined || this.activeAppKey.trim().length === 0) {
        this.activeAppKey = sessionStorage.getItem(AppConstants.APP_KEY);
      }
      

      【讨论】:

        【解决方案5】:

        我会采用这种方法。创建一些 util 类并将其添加为静态方法。

        export class Util {
          static isNullOrUndefined<T>(obj: T | null | undefined): obj is null | undefined {
            return typeof obj === 'undefined' || obj === null;
          }
        }
        
        

        【讨论】:

          【解决方案6】:

          您可以使用core-util-is npm 包中的isNullOrUndefined 函数。

          它已从 nodejs 核心中弃用,因为这些函数的行为或 api 更改可能会在不通知用户的情况下破坏大量现有代码。在一个 npm 包中,使用 semver,只有一个主要版本的碰撞才能破坏 api/behaviour。这样更安全。

          【讨论】:

            【解决方案7】:

            来自 NodeJs 参考 [https://nodejs.org/api/util.html#utilisnullorundefinedobject]:

            已弃用:改用value === undefined || value === null

            这使得上面超级IT人给出的答案正确(https://stackoverflow.com/a/56138823/6757814

            【讨论】:

              猜你喜欢
              • 2011-08-11
              • 1970-01-01
              • 1970-01-01
              • 2013-10-12
              • 1970-01-01
              • 2016-03-03
              • 1970-01-01
              • 2023-03-27
              • 2013-08-08
              相关资源
              最近更新 更多