angular - 异步管道不应被否定

标签 angular eslint tslint codelyzer

我按照 the guide 从 TSLint 迁移到 ESLint 。现在,我收到此错误消息:

Async pipes should not be negated. Use (observable | async) === (false | null | undefined) to check its value instead

这是given explanation :

Angular’s async pipes emit null initially, prior to the observable emitting any values, or the promise resolving. This can cause negations, like *ngIf=”!(myConditional | async)” to thrash the layout and cause expensive side-effects like firing off XHR requests for a component which should not be shown.

但我不明白建议的解决方案,特别是按位或:false | null | undefined 。当我尝试写(false | null | undefined)时在模板中,Angular 似乎考虑 nullundefined作为管道(看起来合法)并抛出错误消息。即使在 html 模板之外,这个按位“或”也只是返回 0,那么这有什么意义呢?我也尝试过false || null || undefined但它实际上相当于 undefined

我错过了什么吗?或者错误消息具有误导性?那我该怎么写呢?

我拥有的最好的就是这个,但它非常丑陋:

(observable | async) === false || (observable | async) === undefined

最佳答案

作为比较可观察值的另一种方法,您可以创建自己的管道:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'isFalsy',
  pure: false,
})
export class IsFalsyPipe implements PipeTransform {
  transform(value: any): any {
    return value ? false : true;
  }
}

导入您的模块,然后像这样比较:

<div *ngIf="observable$ | async | isFalsy"></div>

关于angular - 异步管道不应被否定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67609935/

相关文章:

node.js - 尽管项目在 docker 容器上,但如何在我的 IDE 上提供 linting 功能?

javascript - 是否有 ESLint 规则可以检查条件表达式中逻辑运算符的数量?

javascript - 在 TSLint 中禁用正则表达式对某些字符串的使用?

javascript - ESLint 规则排除 Angular 中的某些关键字和短语?

angular - 升级到 EsLint : Error with angular. json(原理图:convert-tslint-to-eslint)

Angular - 动态包含或删除拦截器

Angular Material 网格,rowHeight适合

angular - @angular/cdk/overlay 全局和居中位置不起作用

angular - 如何使用 tslint 在特定文件中导入黑名单

angular - 如何在 Angular 2中为不同的路线使用不同的路由器导出