我按照 the guide 从 TSLint 迁移到 ESLint 。现在,我收到此错误消息:
Async pipes should not be negated. Use (observable | async) === (false | null | undefined) to check its value instead
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 似乎考虑 null
和undefined
作为管道(看起来合法)并抛出错误消息。即使在 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/