【问题标题】:Does .includes() run during a change detection loop if the variable associated with it does not change? / Alternative to .includes().includes() 如果与之关联的变量没有变化,是否会在变化检测循环期间运行? / 替代 .includes()
【发布时间】:2021-06-20 06:15:19
【问题描述】:

我的组件文件中有一个变量 user_roles,它由ngInit() 上的 API 初始化,之后不会更改。

this.service.getUserRoles().subscribe(
      data => {
        this.user_roles = data;
      }
    )

user_roles 是一个数组,其中包含该用户的权限:user_roles = ['admin', 'mediator', ...]

在我的模板中,我有显示基于 user_role 的组件的代码:

<div *ngIf="user_roles.includes('admins') || user_roles.includes('mediator')">

    <div ....
    .
    . 
    .

.includes() 是否会在其他一些变量发生变化并且变化检测循环运行时运行?如果是这样,那么我可以使用什么替代方法来提高性能?

【问题讨论】:

  • 自己查看的一种方法是在 Typescript 中创建一个 getter,它执行 console.log 并使用它而不是模板中的直接变量
  • 还有一种优化方法是只计算一次条件并将结果存储在一个变量中。不过,我不相信它会对您的示例产生如此大的影响。

标签: html angular typescript angular-ng-if front-end-optimization


【解决方案1】:

会的。

angular 更改检测并不意味着如果属性更改,则更新其依赖项。这实际上是vue 方式。实际上angular 更改检测意味着每次异步操作(Promise event setTimout) 发生时,重新评估每个模板绑定。所以是的,includes 将再次被调用。

最简单的验证方式如下

const orig = Array.prototype.includes
Array.prototype.includes = function<T> (arg: T) {
    console.log(this, arg)
    orig.call(this, arg)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-25
    • 1970-01-01
    • 2021-09-22
    • 2021-06-17
    相关资源
    最近更新 更多